将 0 和 1 的字符串转换为字符的简单方法?普通C
我正在做一个隐写术项目,我从 ppm 文件中读取字节并将最低有效位添加到数组中。因此,一旦读入 8 个字节,我的数组中就会有 8 位,这应该等于隐藏消息中的某个字符。有没有一种简单的方法可以将 0 和 1 的数组转换为 ASCII 值?例如,数组:char bits[] = {0,1,1,1,0,1,0,0}
等于“t”。 Plain C
感谢您的所有回答。我要尝试其中一些。
I'm doing a steganography project where I read in bytes from a ppm file and add the least significant bit to an array. So once 8 bytes are read in, I would have 8 bits in my array, which should equal some character in a hidden message. Is there an easy way to convert an array of 0's and 1's into an ascii value? For example, the array: char bits[] = {0,1,1,1,0,1,0,0}
would equal 't'. Plain C
Thanks for all the answers. I'm gonna give some of these a shot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一个简单的
for
循环就可以工作 - 就像There might be a better way to do this,但这至少是一个开始。
A simple
for
loop would work - something likeThere might be a faster way to do this, but this is a start at least.
我不会将这些位存储在数组中 - 我会将它们与字符进行“或”运算。
因此,您从 char 值 0 开始:
char bit = 0;
当您获得第一个位时,将其与您拥有的值进行或:
bit |= bit_just_read;
保留对每一位都这样做,适当地移动;即,在获得下一位后,执行
bit |= (next_bit << 1);
。等等。读取 8 位后,
bit
将是适当的 ASCII 值,您可以将其打印出来或用它做任何您想做的事情。I wouldn't store the bits in an array -- I'd OR them with a char.
So you start off with a char value of 0:
char bit = 0;
When you get the first bit, OR it with what you have:
bit |= bit_just_read;
Keep doing that with each bit, shifting appropriately; i.e., after you get the next bit, do
bit |= (next_bit << 1);
. And so forth.After you read your 8 bits,
bit
will be the appropriate ASCII value, and you can print it out or do whatever with it you want to do.我同意 mipadi 的观点,不要先费心存储在数组中,那是毫无意义的。由于在读入数组时必须循环或以其他方式跟踪数组索引,因此您不妨一次性完成。也许是这样的?
I agree with mipadi, don't bother storing in an array first, that's kind of pointless. Since you have to loop or otherwise keep track of the array index while reading it in, you might as well do it in one go. Something like this, perhaps?
只要位字节顺序正确,就应该可以工作并且编译得非常小。
如果位尾数向后,那么您应该能够将 mask 的初始值更改为 1,将 mask 更改为 <<= ,并且您可能需要将 (0x0ff & mask) 作为 do{}while 条件如果您的编译器没有对字节大小的变量执行应有的操作。
不要忘记为我包含的神奇功能做一些事情,而我不知道你想要什么或你如何做某事
As long as the bit endian is correct, this should work and compile down pretty small.
If the bit endian is backwards then you should be able to change the initial value of mask to 1, the mask shift to <<= , and you might need to have (0x0ff & mask) as the do{}while conditional if your compiler doesn't do what it's supposed to with byte sized variables.
Don't forget to do something for the magic functions that I included where I didn't know what you wanted or how you did something