How can I copy several bits into a binary number or how can I reset some bits with one command ?
I can select a section from the number with original number & ~ (~0 << length of section )
Thanks
Tepy
This is a discussion on copy some bits into a 8 bits binary number within the C Programming forums, part of the General Programming Boards category; How can I copy several bits into a binary number or how can I reset some bits with one command ...
How can I copy several bits into a binary number or how can I reset some bits with one command ?
I can select a section from the number with original number & ~ (~0 << length of section )
Thanks
Tepy
You can OR them into the number with this '|=' and extract them with '&='.
24bbs.cppCode:if( numeric_limits< byte >::digits != bits_per_byte ) error( "program requires bits_per_byte-bit bytes" );
For example resetting bit 1 of a byte:
/* Define a mask */
#define RESET_BIT_1 0xF2 /* 1111:1101 */
unsigned char byte;
byte &= RESET_BIT_1;
Thanks the ideas, I try them.
Tepy
Unfortunately I can't use this for my problem. I need some ideas for example how I can change some bits in a bitstream.
For examle the source bitstream is 11100111, the sample bits let 100. I want to change the source bitstream's second, third and fourth bit with 100.
Thanks
Tepy
Then you could consider using bitfields.
More easier than mapping is the use of a union. LikeCode:/* Define a bitfield */ typedef struct { unsigned int b0:1; unsigned int b1:1; unsigned int b2:1; unsigned int b3:1; unsigned int b4:1; unsigned int b5:1; unsigned int b6:1; unsigned int b7:1; } bitfield_s; void function () { unsigned char *var1; bitfield_s *var2; /* The bitstream */ *var1 = 0xF0; printf ("%02X\n", *var1); /* Map it on a bitfield */ var2 = (bitfield_s *) var1; /* Manipulate bits */ var2->b0 = 1; var2->b1 = 1; var2->b2 = 1; var2->b3 = 1; var2->b4 = 0; var2->b5 = 0; var2->b6 = 0; var2->b7 = 0; /* Put it back */ var1 = (unsigned char *) var2; printf ("%02X\n", *var1); }
Code:typedef union { bitfield_s bitfield; unsigned char byte; } byte_u; void function (void) { byte_u var1; var1.byte = 0xF0; printf ("%02X\n", var1.byte); /* Manipulate bits */ var1.bitfield.b0 = 1; var1.bitfield.b1 = 1; var1.bitfield.b2 = 1; var1.bitfield.b3 = 1; var1.bitfield.b4 = 0; var1.bitfield.b5 = 0; var1.bitfield.b6 = 0; var1.bitfield.b7 = 0; printf ("%02X\n", var1.byte); }
> Unfortunately I can't use this for my problem. I need some ideas for example how I can change some bits in a bitstream.
Of course you can use it for a bitstream. This is called bitwise manipulation and is how you do it in the most effecient manner.
You create a mask for each bit and then manipulate each bit using the value and the mask.
Go to the library, or the bookstore, and look at 'bitwise' or 'bit manipulation' in one of their chapters.