简体   繁体   中英

Dummy output from an unsigned char buffer

I am using a C++ code to read some binary output from an electronic board through USB. The output is stored on an unsigned char buffer. When I'm trying to print out the value or write it to an output file, I get dummy output instead of hex and binary value, as shown here:

햻"햻"㤧햻"㤧햻"햻"㤧

This is the output file declaration:

f_out.open(outfilename, ios::out);
if (false == f_out.is_open()) {
    printf("Error: Output file could not be opened.\n");
    return(false);
}

This is the output command:

xem->ReadFromPipeOut(0xA3, 32, buf2);
f_out.write((char*)buf2, 32);
//f_out << buf2;

"xem" is a class for the USB communication. ReadFromPipeOut method, reads the output from the board and stores it on the buffer buf2. This is the buffer definition inside the main:

unsigned char buf2[32];

Why do you expect hex output? You ask to write char s, it writes char s.

To output hex values, you can do this:

f_out << std::hex;
for (auto v : buf2)
    f_out << +v << ' ';

To get numbers in the output, values should be output as integers, not as characters. +v converts unsigned char into unsigned int thanks to integral promotion . You can be more explicit about it and use static_cast<unsigned int>(v) .

unsigned char buf[3] = {0x12, 0x34, 0x56};
std::cout << std::hex;
for (auto v : buf)
    std::cout << static_cast<unsigned int>(v) << ' ';
// Output: 12 34 56

To output numbers as binary:

for (auto v : buf)
    std::cout << std::bitset<8>(v) << ' ';

(no need for std::hex and static_cast here)

To reverse the order:

for (auto it = std::rbegin(buf); it != std::rend(buf); ++it)
    std::cout << std::bitset<8>(*it) << ' ';

Note that the order of bytes in a multi-byte integer depends on endian-ness . On a little-endian machine the order is reserved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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