1

I have am array of chars that I'm using for bytecode. Printing them out one by one should yield the same hex values that you see here:

char toWrite[] = {'\x50','\x48','\xB8','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\xFF','\xE0' };

When I try to print these values out in a loop, however, they are mangled. What I see instead is:

50 48 ffffffb8 00 00 00 00 00 00 00 ffffffff ffffffe0

Why are these chars printing wrong? I am iterating in a foreach loop, and every single element is passed to

cout << hex << (int)currentChar << endl;
2
  • One option is to cast differently, (int)(unsigned char)currentChar Commented Feb 20, 2017 at 1:52
  • 1
    Please don't advocate c-style casts, static_cast should always be preferred to tell the compiler the intention. Commented Feb 20, 2017 at 2:10

1 Answer 1

3

For most systems, char is 8 bits wide and is a signed integer type. Storing \xB8 will make its most significant bit 1, which will make it negative. And casting it to int will also result in a negative value, resulting in 0xffffffb8 if int is 32 bits wide.

You should use unsigned char:

unsigned char toWrite[] = {/*...*/};

Also, static_cast is more preferable than C-style cast:

cout << hex << static_cast<int>(currentChar) << endl;
Sign up to request clarification or add additional context in comments.

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.