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.
3 Answers
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.

- 123,740
- 17
- 206
- 299
-
its just char buffer[size]; and you were right in that first part. casting it twice works. but casting it just to unsigned int gets -1. – gemexas Jan 16 '11 at 16:00
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.)

- 1
- 1

- 530,221
- 131
- 937
- 1,214
-
@gemexas: correct, look at Matteo’s answer for an explanation why that is and how to fix it. Although this **should** work for `unsigned char` … – Konrad Rudolph Jan 16 '11 at 15:58
Using stringstream (http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/) would be one viable solution, converting the byte (Which, I imagine is just an unsigned char) to an integer stored as a string.

- 1,621
- 1
- 13
- 12