简体   繁体   English

如何将 uint8_t 的二进制表示读取为数字

[英]How to read binary representation of uint8_t as a number

I write binary representation of a uint8_t sequence in file with the next code我用下一个代码在文件中编写 uint8_t 序列的二进制表示

uint8_t toStore;

std::fstream file("input", std::ios::binary | std::ios::out);
while(std::cin >> toStore) {
    file.write((char*)&toStore, sizeof(toStore));
}
file.close()

And then read it然后阅读它

file.open("input", std::ios::binary | std::ios::in);
file.read((char*)&toStore, sizeof(toStore));
while(!file.eof()) {
   std::cout << toStore << " ";
   file.read((char*)&toStore, sizeof(toStore));
}
file.close();

But when I read next sequence ("255 1 5", for example) which I write in a file with represented code with the above code I get但是,当我读取下一个序列(例如“255 1 5”)时,我将其写入文件中,并使用上述代码表示代码,我得到

2 5 5 1 5

Instead of代替

255 1 5

Can I read a number sequence, not character?我可以读取数字序列,而不是字符吗?

The problem is both with reading uint8_t from cin and with writing it to cout .问题在于从cin读取uint8_t并将其写入cout

Already discussed in many previous SO questions, eg How to read numeric data as uint8_t .已经在许多以前的 SO 问题中讨论过,例如How to read numeric data as uint8_t

uint8_t and int8_t are typedefs for unsigned char and signed char respectively, thus treated by istream and ostream as char . uint8_tint8_t分别是unsigned charsigned char类型定义,因此被istreamostream视为char

A possible solution:一个可能的解决方案:

bool read_one_byte(std::istream & is, uint8_t& out)
{
    short x;
    if (is >> x)
    {
        // can check here if number exceeds uint8_t ignore it or do something else...
        // current code doesn't check
        out = static_cast<uint8_t>(x);
        return true;
    }
    return false;
}

void print_one_byte(std::ostream & os, uint8_t val)
{
    os << static_cast<short>(val);
}

Then use it:然后使用它:

int main() {
    uint8_t toStore;
    std::fstream file("input", std::ios::binary | std::ios::out);
    while(read_one_byte(std::cin, toStore)) {
        uint8_t toStore2 = toStore;
        std::cout << "writing to file: " << (int)toStore2 << std::endl;
        file.write((char*)&toStore2, sizeof(toStore2));
    }
    file.close();
    file.open("input", std::ios::binary | std::ios::in);
    std::cout << "reading from file: ";
    file.read((char*)&toStore, sizeof(toStore));
    while(!file.eof()) {
        print_one_byte(std::cout, toStore);
        std::cout << ' ';
        file.read((char*)&toStore, sizeof(toStore));
    }
    file.close();
}

http://coliru.stacked-crooked.com/a/839e2d495214a336 http://coliru.stacked-crooked.com/a/839e2d495214a336

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

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