Adding hexadecimal to string

Viewed 37

I'm trying to add a single 1 bit to a string, however, it seems that I keep getting the char converted to an int. I've tried typecasting it to an unsigned char, but I think that it's still converting it.

string output = "abc";
output += 0x80;
for (char c : output) printf("%02x", c);

I keep getting 616263ffffff80. However, I'm trying to get it to be 61626380;

1 Answers

The problem is your printf. It's using %x which expects a unsigned int value. However, your c value is signed char. And so this value is converted to the equivalent integer which happens to be 0xffffff80.

You can correct this in various ways:

  1. Use unsigned value for your loop variable:

     for (unsigned char c : output) printf("%02x", c);
    
  2. Cast the value to unsigned char:

     for (char c : output) printf("%02x", (unsigned char)c);
    
  3. Use the appropriate format length modifier:

     for (char c : output) printf("%02hhx", c);
    
Related