Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char array to hex string conversion - unexpected output

Tags:

c++

I have a simple program converting dynamic char array to hex string representation.

#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
using namespace std;


int main(int argc, char const* argv[]) {
    int length = 2;
    char *buf = new char[length];
    buf[0] = 0xFC;
    buf[1] = 0x01;

    stringstream ss;
    ss << hex << setfill('0');
    for(int i = 0; i < length; ++i) {
        ss << std::hex << std::setfill('0') << std::setw(2) << (int) buf[i] << " ";
    }
    string mystr = ss.str();
    cout << mystr << endl;
}

Output:

fffffffc 01

Expected output:

fc 01

Why is this happening? What are those ffffff before fc? This happens only on certain bytes, as you can see the 0x01 is formatted correctly.

like image 885
Martinez Avatar asked Mar 04 '26 23:03

Martinez


1 Answers

Three things you need to know to understand what's happening:

  1. The first thing is that char can be either signed or unsigned, it's implementation (compiler) specific

  2. When converting a small signed type to a large signed type (like e.g. a signed char to an int), they will be sign extended

  3. How negative values are stored using the most common two's complement system, where the highest bit in a value defines if a value is negative (bit is set) or not (bit is clear)

What happens here is that char seems to be signed, and 0xfc is considered a negative value, and when you convert 0xfc to an int it will be sign-extended to 0xfffffffc.

To solve it use explicitly unsigned char and convert to unsigned int.

like image 197
Some programmer dude Avatar answered Mar 06 '26 11:03

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!