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 chars.

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

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -