Reputation: 131
I'm trying to figure out a way to split a byte into two (eg. F8
to F
and 8
) to be later recombined with other bytes. I read up on bit masking but I still don't quite understand it. This is what I'm trying to do.
F8 FF FF
- Split the bytes into two. I'll use variables to distinguish the bytes
u=F
, v=8
, w=F
, x=F
, y=F
, z=F
, which are essentially, uv
, wx
, yz
The end result would be FF8 FFF
or in variables, xuv
yzw
.
Does anyone know how to do this? Thanks in advance!
Upvotes: 0
Views: 1065
Reputation: 94409
If you aren't too familiar with logical operators, I suggest to introduce two little helper functions to encapsulate this stuff:
void split_nibbles( unsigned char ch, unsigned char *higherOrder, unsighed char *lowerOrder )
{
*higherOrder = ch >> 4;
*lowerOrder = ch & 0x0f;
}
unsigned char merge_nibbles( unsigned char higherOrder, unsigned char lowerOrder )
{
return (higherOrder << 4) | (lowerOrder & 0x0f);
}
You can then write
unsigned char bytes[] = { 0xf8, 0xff, 0xff };
unsigned char u, v, w, x, y, z;
split_nibbles( bytes[0], &u, &v );
split_nibbles( bytes[1], &w, &x );
split_nibbles( bytes[2], &y, &z );
bytes[0] = merge_nibbles( x, u );
bytes[1] = merge_nibbles( v, y );
bytes[2] = merge_nibbles( z, w );
...which is very close to your description. :-)
Upvotes: 1
Reputation: 127538
If you have a variable x
with a value known to fit into one byte, you can split it into two nibbles like this:
x_lo = x & 0xf;
x_hi = (x >> 4) & 0xf;
To combine two nibbles y_lo
and y_hi
into one byte you shift and or:
y = y_lo | (y_hi << 4);
Upvotes: 2