1

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.

1
  • yeah, its not implemented yet. the point is to print buffer[5] as 255. or assign buffer to int as 255. Commented Jan 16, 2011 at 15:50

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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 Comment

@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
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.