Set Least Significant Bit in C

Angelos Mouzakitis picture Angelos Mouzakitis · Nov 2, 2013 · Viewed 8.3k times · Source

I write a simple steganography tool in C with bmp images.

I read the image to memory and the text to hide in char bytes[8] one character at a time.

so eg.

a=0d97
bytes[0] = 0
bytes[1] = 1
bytes[2] = 1
bytes[3] = 0
bytes[4] = 0
bytes[5] = 0
bytes[6] = 0
bytes[7] = 1

Then i 'll go to the first image byte(char *ptr points it every time) to put the bytes[0] to LSB, then the next one etc.

If the *ptr=0xff or 0b11111111 i have to set the last 1 to 0. This can be with

*ptr = *ptr ^ 0x01 ;

but if the *ptr = 0x00 or 0b00000000 the xor doesent work because 0^1=1

I 'm confused how to set the case. I need a operator to make the last bit every time 0 and not touch the others in case LSB is 1 or 0.

Answer

Mark Tolonen picture Mark Tolonen · Nov 2, 2013

Use this pattern to set the least significant bit to the value in bit (0 or 1):

new_value = old_value & 0xFE | bit

The AND will turn off bit zero and the OR will turn it back on if bit is 1.