Link to home
Start Free TrialLog in
Avatar of AndreeaN
AndreeaN

asked on

Splitting up a bit into 2 x 4 bits

Hi All,

I'm reading in some data from a file like so:

char * code = new char[1];
infile.read(code, 1);

Within this byte of data there are two numbers I need to extract - they are represented by the first 4 bits and the second four bits - how to go about splitting the byte up and extracting both numbers?

Thanks
Avatar of jkr
jkr
Flag of Germany image

You can do that using the following macros, which in turn use bit masking and shifting:
#define LO(x) (x & 0x0F) // extracts the lower four bits
#define HI(x) ((x & 0xF0) >> 4) // extracts the upper four bits and shifts them down by 4
 
int upper = HI(*code);
int lower = LO(*code);

Open in new window

Avatar of AndreeaN
AndreeaN

ASKER

Hmm, I have no doubt that will work, but since I have not done any bitmasking before, could you explain how what you have there extracts the two parts? Also, if possible, could you show me a non-macroed solution?
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Bang. There we go - awesome, thanks.
If you use that solution (with a right-shift in it), then make sure to use an unsigned char, and not just a char. As a rule, when bit shifting is involved, always use unsigned integer types !!