# Thread: copy some bits into a 8 bits binary number

1. ## copy some bits into a 8 bits binary number

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 2. You can OR them into the number with this '|=' and extract them with '&='. 3. 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; 4. ## Thanks the ideas, I try them.

Tepy 5. ## 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 6. Then you could consider using bitfields.

Code:
```/* 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);
}```
More easier than mapping is the use of a union. Like

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);
}``` 7. > 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. Popular pages Recent additions 