简体   繁体   中英

Getting byte value from char

It simple but I am getting problem with this. http://www.ipix.lt/images/90928843.png I want to cout buffer[5]. But not the symbol value, but 255. Tried typecasting to int or byte but that gets -1.

It's correct that, casting it to int, you get -1, because char in your implementation is a signed type (it's actually implementation-defined if char is signed or unsigned, and usually you can change it in the compiler options); what you see in the debugger window is it's unsigned representation.

To get its unsigned value you should first cast it to unsigned char and then to unsigned int (I think you could also get away with just casting it to unsigned int , but I'm not sure).

---EDIT---

Actually in the debugger window I see its type as unsigned char , so the first part of my answer may not apply... you should tell us how is that buffer defined.

How is byte defined? C++ knows no such type.

You can cast to int however:

static_cast<int>(msg.buffer[i + 2]) …

Note the use of static_cast instead of the deprecated C-style casts. Always use the former, never the latter. For explanation on why, see the question on C++ cast syntax style .

(Adding to that, Matteo is right in that you need to cast to an unsigned value first.)

使用stringstream(http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/)是一个可行的解决方案,将字节(我想这只是一个无符号字符)转换为存储的整数作为字符串。

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