0

In this code:

// read bootrom
std::ifstream bootrom_file (bootrom_path, std::ios::binary | std::ios::ate);
const int bootrom_size = bootrom_file.tellg();
bootrom_file.seekg(0, std::ios_base::beg);
// allocate bootrom_size bytes for the bootrom vector
bootrom.resize(bootrom_size);
if(bootrom_size != 0x100)
{
    std::cerr << "boot ROM is not 256 bytes!\n";
}
if(bootrom_file)
{
    bootrom_file.read(reinterpret_cast<char*>(bootrom.data()), bootrom_size);
}
// prints 0xC3 0x31
printf("%#02x  %#02x\n", rom[0], bootrom[0]);
// prints ?  1
std::cout << std::hex << rom[0] << "  " << std::hex << bootrom[0] << "\n";

std::cout prints out ? 1, but printf prints out 0xC3 0x31 which is correct. What am I doing wrong here?

Note that rom and bootrom are both std::vector of uint8_t, and rom is set using the same code as bootrom.

Ryan Terry
  • 181
  • 8
  • Is `rom` a `char` array? Try `(int)rom[0]`. – AlexD Mar 26 '17 at 15:38
  • I added in there that it is a vector uint8_t – Ryan Terry Mar 26 '17 at 15:41
  • It is likely you have something like `typedef unsigned char uint8_t;` so `cout` prints characters. – AlexD Mar 26 '17 at 15:43
  • I don't have it, uint8_t is defined in the standard (albeit as a char, yes). And I just learned that this is the reason, thanks. It prints out the ascii character. – Ryan Terry Mar 26 '17 at 15:47
  • The standard does not specify `uint8_t` precisely. It says: `typedef unsigned integer type uint8_t; // optional` – AlexD Mar 26 '17 at 15:49
  • I think it's `typedef unsigned char uint8_t`, afaik – Ryan Terry Mar 26 '17 at 15:55
  • I copy-pasted the `typedef` above from the standard. It is not precisely defined (and even optional). – AlexD Mar 26 '17 at 16:00
  • Oh gotcha, well it is unsigned char in gnu – Ryan Terry Mar 26 '17 at 19:57
  • [cout not printing unsigned char](https://stackoverflow.com/q/15585267/995714), [std::cout deal with uint8_t as a character](https://stackoverflow.com/q/39145753/995714), [uint8_t can't be printed with cout](https://stackoverflow.com/q/19562103/995714), [Does the unary + operator have any practical use?](https://stackoverflow.com/a/14365849/995714) – phuclv Sep 03 '18 at 10:09
  • 1
    Possible duplicate of [uint8\_t can't be printed with cout](https://stackoverflow.com/questions/19562103/uint8-t-cant-be-printed-with-cout) – phuclv Sep 03 '18 at 10:09
  • I think you need to `bootrom_file.seekg(0, std::ios_base::end);` when calculating `bootrom_size`. The call to `bootrom_file.seekg(0, std::ios_base::beg);` is still needed after `tellg()`. – jww Sep 03 '18 at 12:03

1 Answers1

2

Solution: I figured it out. Turns out that std::cout cannot print uint8_t by value since it is a typedef char, so it prints the ascii character instead.

Ryan Terry
  • 181
  • 8