0

使用C++,我正在尝试从如下所示的文件中读取:

111111100100000000001101
100011100000000000000000
111111000100000000101001
001011110100000000000011
001111000100000000000110

每行代表 3 个字节,我想使用uint8_t.

我写了这段代码,在 while 循环中,为了简单起见,我只取每一行的第一个字节:

    uint8_t * buffer = new uint8_t[lSize];
    memset(buffer, 0, lSize);
    ifstream file(argv[1]);
    string str;
    int i=0;
    while(getline(file, str)){
        string byte = str.substr(0,8);
        bitset<8> bitsaddress(byte);
        int number = bitsaddress.to_ulong();
        buffer[i]=number;
        cout << buffer[i]<<endl;
        i++;
    }

但是shell上的输出是这样的:

-
�
�
'

-
e
N
k

如果我打印变量number而不是buffer[i]我有正确的行为。

我不明白为什么会发生这种情况,有人可以解释吗?

4

2 回答 2

1

打印字符是一个字节表示的所有值的子集。从 32 到 126 的所有值都由您可以识别为字符的东西在视觉上表示,但其余的值不是。其他一些值会执行您会识别的操作,例如添加换行符或发出哔声,但取决于您的终端如何解释其他所有内容,您将在终端上得到不同形式的乱码。

为了调试,尝试将所有结果打印为整数或十六进制字符串。

于 2015-03-27T00:59:58.527 回答
0

干得好:

ifstream myFile("myFile");
assert(myFile.is_open()); // #include <cassert>

string str;
vector<uint8_t> vec;
int count = 0;

while (getline(myFile, str)) {
    uint8_t tmp = 0;
    for (const auto& c : str) {
        count++;
        tmp <<= 0x1;
        tmp |= (c - '0');
        if (count >= 8) {
            vec.push_back(tmp);
            tmp     = 0;
            count   = 0;
        }
    }
}

myFile.close();

for (const auto& v : vec) cout << (uint32_t)v << endl;
于 2015-03-27T01:07:05.837 回答