简体   繁体   English

在C ++中将0和1的char数组转换为字节

[英]Convert a char array of 0 and 1 to bytes in C++

I have a question here. 我在这里有一个问题。 It might sound trivial to you but not for me since I'm pretty much still a noob in C++. 这听起来对您来说微不足道,但对我而言却并非如此,因为我在C ++中还是个菜鸟。 (also sorry for my limited english knowledge) (也对我有限的英语知识感到抱歉)

Let's say I have a char a[72] array. 假设我有一个char a[72]数组。 This array is filled with '0' and '1' representing bits ( a[0] = '0' , a[1] = '1' , a[2] = '1' etc.) and I need to save this as a binary file, so when I try to view this file with xxd -b i would like to see these 9 bytes as they were in the array. 该数组填充有代表位的'0''1'a[0] = '0'a[1] = '1'a[2] = '1'等),我需要保存作为二进制文件,因此当我尝试使用xxd -b查看此文件时,我希望看到这9个字节,就像它们在数组中一样。

Could please anybody lead me to the solution how to convert this char array? 可以请任何人带我到解决方案中如何转换此char数组吗?

You need to split your array in groups of 8 symbols and convert each group from binary string representation to unsigned char. 您需要将数组分成8个符号的组,并将每个组从二进制字符串表示形式转换为无符号字符。 For example: 例如:

unsigned char byte = 0;
for( int i = 0; i < 8; ++i )
    if( a[i] == '1' ) byte |= 1 << (7-i);

Then put that bytes into another array size 72/8 and store it into file, for example by std::ostream::write() method. 然后将该字节放入另一个大小为72/8的数组中,并将其存储到文件中,例如通过std::ostream::write()方法。 You may group bits by 16, 32 or 64 bits and use uint16_t , uint32_t or uint64_t for values, but this way is most simple and you probably should start with it and make it work first. 您可以按16、32或64位对位进行分组,并使用uint16_tuint32_tuint64_t作为值,但是这种方式最简单,您可能应该从它开始并使其首先起作用。

Perhaps something like this? 也许像这样?

const std::size_t n = 72;
std::vector<char> byteArray(n / 8);

for (std::size_t i = 0; i < n / 8; ++i)
    for (std::size_t j = 0; j < 8; ++j)
        if (a[i * 8 + j] == '1')
            byteArray[i] |= 1 << j;

Then access byteArray with operator[]() or data() . 然后使用operator[]()data()访问byteArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM