简体   繁体   中英

Writing on MSB and on LSB of an unsigned Char

I have an unsigned char and i want to write 0x06 on the four most significant, and i want to write 0x04 on its 4 least significant bits. So the Char representation should be like 0110 0010

Can some can guide me how i can do this in C?

c = (0x06 << 4) | 0x04;

Because:

0x04    = 0000 0100
0x06    = 0000 0110

0x06<<4 = 0110 0000
or op:  = 0110 0100

Shift values into the right position with the bitwise shift operators, and combine with bitwise or .

unsigned char c = (0x6 << 4) | 0x4;

To reverse the process and extract bitfields, you can use bitwise and with a mask containing just the bits you're interested in:

unsigned char lo4 = c & 0xf;
unsigned char hi4 = c >> 4;

First, ensure there are eight bits per unsigned char :

#include <limits.h>
#if CHAR_BIT != 8
    #error "This code does not support character sizes other than 8 bits."
#endif

Now, suppose you already have an unsigned char defined with:

unsigned char x;

Then, if you want to completely set an unsigned char to have 6 in the high four bits and 4 in the low four bits, use:

x = 0x64;

If you want to see the high bits to a and the low bits to b , then use:

// Shift a to high four bits and combine with b.
x = a << 4 | b;

If you want to set the high bits to a and leave the low bits unchanged, use:

// Shift a to high four bits, extract low four bits of x, and combine.
x = a << 4 | x & 0xf;

If you want to set the low bits to b and leave the high bits unchanged, use:

// Extract high four bits of x and combine with b.
x = x & 0xf0 | b;

The above presumes that a and b contain only four-bit values. If they might have other bits set, use (a & 0xf) and (b & 0xf) in place of a and b above, respectively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM