Slice a byte.

Started by
4 comments, last by DaA 20 years, 6 months ago
I´ve got a char (1 byte) or 8 bits, and want to use the last 4 bits but how can I delete the first 4 bits.
Advertisement
Use the & operator:

char a = 255; // 1111 1111
a = a & 0x0f; // 0000 1111
myByte &= ~(0xF0);
"I thought Genius lived in bottles..." - Patrick Star
Mask them using bitwise AND.

Niko Suni

What language are you using?
I assume c or c++.

to "delete" some bits from a byte, you have to mask them out.
and you can''t really "delete" them, they''re still there, I assume you just want to set them to 0.

You have 8 bits in a byte (as stated)
what you want to do is AND two bytes together.

source_byte = source_byte & mask_byte;

where source_byte is the... source byte
and mask_byte is the mask
by performing a bitwise AND you can blank out specific bits
example:

if the mask were 11111111 (bits)
source_byte & mask_byte would = the original source_byte
(all 1s, no bits ANDed out)
if the mask were 11110000 (again, these are the bits)
source_byte & mask_byte would = xxxx0000 where x are the original bits from source_byte.

Any questions?

-Michael
Thanks...

This topic is closed to new replies.

Advertisement