c++ - ostream.write writes extra bytes into buffer -
i'm using ostream serialize object, write() method seems write bytes buffer.
uint32_t id1=0x01; uint32_t id2=0xdeadbeef; std::stringstream sink; sink.write(reinterpret_cast<char *>(&id1),sizeof(uint32_t)); print(sink); //01000000 - correct sink.write(reinterpret_cast<char *>(&id2),sizeof(uint32_t)); print(sink); //ffffffefffffffbeffffffadffffffde - why?! //print defined follows: static void print(std::ostream &sink){ std::stringstream sk; sk << sink.rdbuf(); std::string ss=sk.str(); for(unsigned int i=0;i<ss.length();i++){ printf("%02x", ss.c_str()[i]); } }
i'm confused why ffff
gets written buffer.
even though ss.c_str()[i]
of type char
, printf
promotes arguments type int
, ffffff
promotion type int
. try "%02hhx"
instead tell printf
convert them unsigned char
s.
another solution ss.c_str()[i] & 0xff
mask them off. also, note ss.c_str()[i]
can simplified ss[i]
.
what happening in code known sign extension.
Comments
Post a Comment