I' ll be honest, this is an homework i just can' t get done.
The task is to handle 8 different checkboxes by using a single byte.
The constructor of the form which contains the checkboxes takes a byte as input and sets the checkboxes to "checked" based on the input.
The flag byte is then stored somewhere and after that each time one checkbox has his status changed (from checked to unchecked and from unchecked to checked) i must change the flag byte accordingly.
So far i was only able to do the first part:
public Form1(byte flags)
{
InitializeComponent();
flags2 = flags;
if ((flags & 0x01) >> 0 != 0) checkBox1.Checked = true;
if ((flags & 0x02) >> 1 != 0) checkBox2.Checked = true;
if ((flags & 0x04) >> 2 != 0) checkBox3.Checked = true;
if ((flags & 0x08) >> 3 != 0) checkBox4.Checked = true;
if ((flags & 0x10) >> 4 != 0) checkBox4.Checked = true;
if ((flags & 0x20) >> 5 != 0) checkBox6.Checked = true;
if ((flags & 0x40) >> 6 != 0) checkBox7.Checked = true;
if ((flags & 0x80) >> 7 != 0) checkBox8.Checked = true;
}
But i really don' t know how to do a not on just 1 bit.
I thought about using additions but then the rest would change the bits to the left.
I can only use this trick on the most significative bit where a rest doesn' t have consequences.
private void checkBox8_CheckedChanged(object sender, EventArgs e)
{
flags2 += 0x80;
}
For the other bits i could really use some help.
To toggle bits, use the XOR operator (^):
flags ^= <bits>; -or- flags2 = flags ^ <bits>; -e.g.- flags ^= 0x04;
To set bits, use the OR operator (|):
flags |= <bits>; -or- flags2 = flags | <bits>; -e.g.- flags |= 0x08;
To clear bits, use the AND operator (&) and the NOT operator (~)
flags &= ~<bits>; -or- flags2 = flags & ~<bits>; -e.g.- flags &= ~0x08;
You have to invert the bit mask:
flags &= ~0x10
will set bit 4 (0x10) to 0.
The ~ operator inverts all bits (8 bit example):
0x10 (0001000)
~0x10 (1110111)
To toggle a bit use this (xor):
flags ^= 0x10
Using additions never works if you want to operate with bits.
For practice, I recommend to write down all numbers as bit masks:
0x10 = 0001000 (base 2)
Supposing that the variable where you have stored the initial status is flags2 then
private void CheckBox1_CheckedChanged(Object sender, EventArgs e)
{
if(checkBox1.Checked)
flags2 |= 1;
else
flags2 &= ~0xFE;
// ~0x2=0xFD, ~0x4=0xFB, ~0x08=0xF7,
// ~0x10=0xF5, ~0x20=0xEB, ~0x40=0xD7, ~0x80=0xAF
}
Also note that your initial test could be rewritten simply as
if ((flags & 0x04) != 0) checkBox1.Checked = true;
Also, you can simplify your initialization code:
checkBox1.Checked = ((flags & 0x01) != 0);
checkBox2.Checked = ((flags & 0x02) != 0);
checkBox3.Checked = ((flags & 0x04) != 0);
checkBox4.Checked = ((flags & 0x08) != 0);
checkBox5.Checked = ((flags & 0x10) != 0);
checkBox6.Checked = ((flags & 0x20) != 0);
checkBox7.Checked = ((flags & 0x40) != 0);
checkBox8.Checked = ((flags & 0x80) != 0);
Related
While I know how to copy one bit from one byte to another (as explained here: Link), I have a problem for a full 4 bit shift from one byte to another byte from a different array (especially for up to 106 bytes).
I read here, how to shift two nibbles at once (for a single byte) and I also tried to implement it:
char *input = (char *)malloc(sizeof(int));
char gen_message[strlen(input) + 1];
for(int loop = (strlen(input) - 1); loop >= 0; loop--)
{
((gen_message[(loop + 1)]) & 0xF0) = ((*input[loop]) & 0x0F);
((gen_message[loop]) & 0x0F) = ((*input[loop]) & 0xF0);
}
gen_message[0] & 0xF0 = 0x4;
Note: Input can between 1 and up to 106 symbols, hence the malloc.
However, I get an error (invalid type of argument of unary '*') and even then I'm not sure if it would be correct.
Can anybody point to a solution or can explain where my brainfart lies, so that I can fix it? Thanks in advance!
-Greetings
Normally (ignoring bitfields) C can't store anything smaller than a char. To work around that you can read the whole char, modify a portion of it, then store the whole (modified) char.
Note that in C char may be signed (e.g. maybe a signed octet with range -128 to +127); and this makes it messy to modify due to uncertainty (e.g. behaviour of "right shift of signed integer" isn't defined). For that reason I'd strongly recommend using unsigned char or uint8_t.
To write the lowest nibble you'd want to do something like:
dest = dest & 0xF0; // Clear all bits in the low nibble
dest = dest | new_nibble; // Set new bits in the low nibble
To write the highest nibble you'd want to do something like:
dest = dest & 0x0F; // Clear all bits in the high nibble
dest = dest | (new_nibble << 4); // Set new bits in the high nibble
To read nibbles you'd do something like:
low_nibble = src & 0x0F;
high_nibble = (src & 0xF0) >> 4;
Copying is just reading and then writing. For example, to copy the lowest nibble from src to the highest nibble in dest you could:
nibble = src & 0x0F;
dest = dest & 0x0F; // Clear all bits in the high nibble
dest = dest | (nibble << 4); // Set new bits in the high nibble
With elements of arrays it might look like this:
nibble1 = input[loop] & 0x0F;
nibble2 = (input[loop] & 0xF0) >> 4;
gen_message[loop + 1] = gen_message[loop + 1] & 0xF0;
gen_message[loop + 1] = gen_message[loop + 1] | nibble1;
gen_message[loop] = gen_message[loop] & 0x0F;
gen_message[loop] = gen_message[loop] | (nibble2 << 4);
This can also be done more concisely:
gen_message[loop + 1] &= 0xF0;
gen_message[loop + 1] |= input[loop] & 0x0F;
gen_message[loop] &= 0x0F;
gen_message[loop] |= ((input[loop] & 0xF0) >> 4) << 4;
Of course if know that the destination contains zeros already (e.g. due to memset() or calloc()), you can skip the "clear nibble" parts:
gen_message[loop + 1] |= input[loop] & 0x0F;
gen_message[loop] |= ((input[loop] & 0xF0) >> 4) << 4;
EDIT
The other commentors are right - due to the number of problems it's hard to guess what you're actually trying to do. I think that you might (but might not) be trying to do something like this:
unsigned char *shiftArray4Bits( unsigned char *srcArray ) {
int srcLen = strlen(srcArray);
unsigned char temp = 0;
unsigned char *destArray;
destArray = malloc(srcLen + 1);
if(destArray == NULL) {
return NULL; // Failed to allocate memory
}
for(int i = 0; i < srcLen; i++) {
dest[i] = temp | ((srcArray[i] & 0xF0) >> 4);
temp = (srcArray[i] & 0x0F) << 4;
}
dest[i] = temp;
return dest;
}
I have this C program that I am writing in code composer studio.
#include <msp430.h>
/*
* main.c
*/
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer
int R5_SW=0, R6_LED=0, temp=0;
P1OUT = 0b00000000; // mov.b #00000000b,&P1OUT
P1DIR = 0b11111111; // mov.b #11111111b,&P1DIR
P2DIR = 0b00000000; // mov.b #00000000b,&P2DIR
while (1)
{
// read all switches and save them in R5_SW
R5_SW = P2IN;
// check for read mode
if (R5_SW & BIT0)
{
R6_LED = R5_SW & (BIT3 | BIT4 | BIT5); // copy the pattern from the switches and mask
P1OUT = R6_LED; // send the pattern out
}
// display rotation mode
else
{
R6_LED = R5_SW & (BIT3|BIT4|BIT5);
// check for direction
if (R5_SW & BIT1) {// rotate left
R6_LED << 1;
} else {
R6_LED >> 1;
} // rotate right
// mask any excessive bits of the pattern and send it out
R6_LED &= 0xFF; // help clear all bits beyound the byte so when you rotate you do not see garbage coming in
P1OUT = R6_LED;
// check for speed
if (R5_SW & BIT2) {__delay_cycles( 40000); } //fast
else {__delay_cycles(100000); } //slow
}
}
}
When it gets to this if statment in debug mode
if (R5_SW & BIT1) {// rotate left
R6_LED << 1;
} else {
R6_LED >> 1;
} // rotate right
It skips over it, it doesn't run the if or the else block. At this point in the code R5_SW is 22 which is 0010 0010 in binary so R5_SW & BIT1 should evaluate to true. What am I missing here?
If you use an operation like << or >> without assigning it then the result is just discarded. Try this:
if (R5_SW & BIT1)
{
R6_LED = R6_LED << 1;
}
else
{
R6_LED = R6_LED >> 1;
}
Or, for brevity:
if (R5_SW & BIT1)
{
R6_LED <<= 1;
}
else
{
R6_LED >>= 1;
}
This piece of code...
if (R5_SW & BIT1) {// rotate left
R6_LED << 1;
} else {
R6_LED >> 1;
} // rotate right
evaluates either the expression R6_LED >> 1 or the expression R6_LED << 1 but it doesn't do anything with the result of it, so the compiler chooses to throw it away the entire IF statement.
A line such as a>>b by itself doesn't modify a. It is not like for example a++ which does modify a.
static uint32_t get_num(void);
uint32_t get_count(unsigned int mask)
{
uint8_t i = 0;
uint32_t count = 0;
while (i < get_num())
{
if (mask & (1 << i++))
count++;
}
return count;
}
In this code, what would be more safe (1L << i++) or (1UL << i++) ?
An unsigned operand is a bit safer because only then is the behavior of all the shifts defined when get_num() returns the number of bits in that operand's type. If unsigned long is wider than unsigned int then UL is slightly safer than just U, but only for accommodating get_num() results that aren't valid anyway.
Safer yet, however, is this:
uint32_t get_count(uint32_t mask)
{
uint8_t num = get_num();
if (num == 0) return 0;
/* mask off the bits we don't want to count */
mask &= ~((uint32_t) 0) >> ((num < 32) ? (32 - num) : 0);
/* count the remaining 1 bits in mask, leaving the result in mask */
mask = (mask & 0x55555555) + ((mask & 0xaaaaaaaa) >> 1);
mask = (mask & 0x33333333) + ((mask & 0xcccccccc) >> 2);
mask = (mask & 0x0f0f0f0f) + ((mask & 0xf0f0f0f0) >> 4);
mask = (mask & 0x00ff00ff) + ((mask & 0xff00ff00) >> 8);
mask = (mask & 0x0000ffff) + ((mask & 0xffff0000) >> 16);
return mask;
}
If you just want to count the 1-bits in an uint and use gcc, you should have a look at the builtin functions (here: int __builtin_popcount (unsigned int x)). These can be expected to be highly optimized and even use special instructions of the CPU where available. (one could very wenn test for gcc).
However, not sure what get_num() would yield - it just seems not to depend on mask, so its output can be used to limit the result of popcount.
The following uses a loop and might be faster than a parallel-add tree on some architectures (one should profile both versions if timing is essential).
unsigned popcount(uint32_t value, unsigned width)
{
unsigned cnt = 0; // actual size intentionally by arch
if ( width < 32 )
value &= (1UL << width) - 1; // limit to actual width
for ( ; value ; value >>= 1 ) {
cnt += value & 1U; // avoids a branch
}
return cnt;
}
Note the width is passed to the function.
On architectures with < 32 bits (PIC, AVR, MSP430, etc.) specialized versions will gain much better results than a single version.
how to reverse the bits using bit wise operators in c language
Eg:
i/p: 10010101
o/p: 10101001
If it's just 8 bits:
u_char in = 0x95;
u_char out = 0;
for (int i = 0; i < 8; ++i) {
out <<= 1;
out |= (in & 0x01);
in >>= 1;
}
Or for bonus points:
u_char in = 0x95;
u_char out = in;
out = (out & 0xaa) >> 1 | (out & 0x55) << 1;
out = (out & 0xcc) >> 2 | (out & 0x33) << 2;
out = (out & 0xf0) >> 4 | (out & 0x0f) << 4;
figuring out how the last one works is an exercise for the reader ;-)
Knuth has a section on Bit reversal in The Art of Computer Programming Vol 4A, bitwise tricks and techniques.
To reverse the bits of a 32 bit number in a divide and conquer fashion he uses magic constants
u0= 1010101010101010, (from -1/(2+1)
u1= 0011001100110011, (from -1/(4+1)
u2= 0000111100001111, (from -1/(16+1)
u3= 0000000011111111, (from -1/(256+1)
Method credited to Henry Warren Jr., Hackers delight.
unsigned int u0 = 0x55555555;
x = (((x >> 1) & u0) | ((x & u0) << 1));
unsigned int u1 = 0x33333333;
x = (((x >> 2) & u1) | ((x & u1) << 2));
unsigned int u2 = 0x0f0f0f0f;
x = (((x >> 4) & u2) | ((x & u2) << 4));
unsigned int u3 = 0x00ff00ff;
x = (((x >> 8) & u3) | ((x & u3) << 8));
x = ((x >> 16) | (x << 16) mod 0x100000000); // reversed
The 16 and 8 bit cases are left as an exercise to the reader.
Well, this might not be the most elegant solution but it is a solution:
int reverseBits(int x) {
int res = 0;
int len = sizeof(x) * 8; // no of bits to reverse
int i, shift, mask;
for(i = 0; i < len; i++) {
mask = 1 << i; //which bit we are at
shift = len - 2*i - 1;
mask &= x;
mask = (shift > 0) ? mask << shift : mask >> -shift;
res |= mask; // mask the bit we work at at shift it to the left
}
return res;
}
Tested it on a sheet of paper and it seemed to work :D
Edit: Yeah, this is indeed very complicated. I dunno why, but I wanted to find a solution without touching the input, so this came to my haead
the data type is char, and the pattern is follow:
source byte: [0][1][2][3][4][5][6][7]
destination: [6][7][4][5][2][3][0][1]
for example, if I pass a char, 29 to this function, it will do the swapping and return a char type value, which is 116.
How can I do the swapping?
thank you.
========================
Just wondering if I can do in this way?
unsigned char mask = 128;
char num = 0, value1 = 29;
int i, a;
for(i = 0; i < 8; i++) {
if (i == 0 || i == 1 || i == 6 || i == 7)
a = 6;
else
a = 2;
if(i < 4)
num = ((value1 & mask) >> a);
else
num = ((value1 & mask) << a);
result = (result | num);
if(i<7)
mask = mask >> 1;
}
I usually number my bits the other way -- so that bit 0 is the LSB. Following your numbering scheme:
unsigned char src = 29;
unsigned char dst = 0;
dst = (((src & 0x80) >> 6) | // bit 0
((src & 0x40) >> 6) | // bit 1
((src & 0x20) >> 2) | // bit 2
((src & 0x10) >> 2) | // bit 3
((src & 0x08) << 2) | // bit 4
((src & 0x04) << 2) | // bit 5
((src & 0x02) << 6) | // bit 6
((src & 0x01) << 6) // bit 7
);
Unless of course, you're numbering them "the right way", but drawing them "backwards" -- then just reverse what I've done above. (Not that I'm trying to start a religious war here...)
or a lookup table
just in case you dont understand that. Here is more detail
For each of the 256 possible inputs work out the answer (by hand)
then do
unsigned char answers[256] = {0x00, 0x40,0x21.....};
unsigned char answer = answers[input];
I hasten to add that the values I gave are an example - and are certainly not correct
See the "Reversing bit sequences" section on Bit Twiddling Hacks.
Also, if you want to do it yourself:
To read the n-th bit: int bit = value & (1 << n); If the bit is not set, bit is 0.
To set the n-th bit: value |= 1 << n; (value = value OR (1 shifted by n digits))
To clear the n-th bit: value &= ~(1 << n); (value = value AND NOT (1 shifted by n digits))
First swap the lower four bits with the higher four bits, then swap all adjacent pairs of bits:
dst = src;
dst = ((dst & 0xF0) >> 4) | ((dst & 0x0F) << 4);
dst = ((dst & 0xCC) >> 2) | ((dst & 0x33) << 2);
You may find this helpful:
http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious
but it the bit reversal there isn't exactly what you need. With just a little work you could change the "obvious" algorithm to do what you want.
source byte: [01][23][45][67] to
destination: [67][45][23][01]
Implementation:
unsigned char shiftit( unsigned char in ) {
unsigned char out;
out = (
(( in & 0xC0 ) >> 6) + /* top 2 to bottom 2 */
(( in & 0x30 ) >> 2) + /* centre-left 2 to centre-right */
(( in & 0x0C ) << 2) + /* centre-right 2 to centre-left */
(( in & 0x03 ) << 6) /* bottom 2 to top 2 */
);
return( out );
}
Returns 116 when called shiftit( 29 ).
Rotate through carry http://en.wikipedia.org/wiki/Bitwise_operation#Rotate_through_carry
So this would work:
myByte = myByte << 2 | myByte >> 6;