Easy way to convert strings 0 and 1 to character? Plain C

I am doing a steganography project where I read in bytes from a ppm file and add the least significant bit to the array. Therefore, as soon as 8 bytes are read, I will have 8 bits in my array, which should equal some character in the hidden message. Is there an easy way to convert an array from 0 and 1 to an ascii value? For example, the array: char bits[] = {0,1,1,1,0,1,0,0} will be equal to 't'. Plain C

Thanks for all the answers. I am going to give some of them a shot.

+4
source share
4 answers

A simple for loop will work - something like

 unsigned char ascii = 0; unsigned char i; for(i = 0; i < 8; i++) ascii |= (bits[7 - i] << i); 

There may be a faster way to do this, but this is at least the beginning.

+4
source

I would not store the bits in an array - I would use them with char.

So, you start with the value char 0: char bit = 0;

When you get the first bit, OR with what you have: bit |= bit_just_read;

Continue to do this with each bit, moving accordingly; those. after you get the next bit, do bit |= (next_bit << 1); . Etc.

After you read your 8 bits, bit will be the appropriate ASCII value, and you can print it or do whatever you want to do with it.

+2
source

I agree with mipadi, do not bother storing in an array, this kind of pointless. Since you need to cyclically or otherwise track the index of an array while reading it, you can also do this at a time. Something like this, maybe?

 bits = 0; for ( i = 0; i < 8; ++i ) { lsb = get_byte_from_ppm_somehow() & 0x01; bits <<= 1 | lsb; } 
0
source

As long as the endian bit is correct, this should work and compile quite a bit. If the end of the bit is in the opposite order, you should be able to change the initial value of the mask by 1, shift the mask by <<=, and you may need (0x0ff and mask) as do {} while conditionally if your compiler doesn’t does what it should use with byte size variables. Do not forget to do something for the magic functions that I turned on, where I did not know what you wanted or how you did something

 #include <stdint.h> // needed for uint8_t ... uint8_t acc, lsb, mask; uint8_t buf[SOME_SIZE]; size_t len = 0; while (is_there_more_ppm_data()) { acc = 0; mask = 0x80; // This is the high bit do { if (!is_there_more() ) { // I don't know what you think should happen if you run out on a non-byte boundary EARLY_END_OF_DATA(); break; } lsb = 1 & get_next_ppm_byte(); acc |= lsb ? mask : 0; // You could use an if statement mask >>= 1; } while (mask); buf[len] = acc; // NOTE: I didn't worry about the running off the end of the buff, but you should. len++; } 
0
source

Source: https://habr.com/ru/post/1305189/


All Articles