-2

I have a string of hex values, and I need it output to a char array so that it can be used as a function input.

std::string firststring = "baaaaaaa";
char bufferascii[128];
std::string firsthash = sha512(firststring);
firsthash.copy(bufferascii, 128,0);
char buffer[64];
for(int i=0; i<64; i++) {
    char temp[4];
    temp[0] = bufferascii[i*2];
    temp[1] = bufferascii[(i*2)+1];
    temp[2] = 0;
    int temp0;
    sscanf(temp, "%x", &temp0);
    buffer[i] = (char)temp0;
    printf("%02x", buffer[i]); printf(" ");
}

Note that the output of sha512(firststring) will be

810dcbf236457fee732f100d261c101412e04fc08abd4cb6ddd4442a7cb690acfcae6eeec25e321d5cf5d63174a3b38b31c0143a5702f5f28a43f38b10742853

However, this code is instead printing:

ffffff81 0d ffffffcb fffffff2 36 45 7f ffffffee 73 2f 10 0d 26 1c 10 14 12 ffffffe0 4f ffffffc0 ffffff8a ffffffbd 4c ffffffb6 ffffffdd ffffffd4 44 2a 7c ffffffb6 ffffff90 ffffffac fffffffc ffffffae 6e ffffffee ffffffc2 5e 32 1d 5c fffffff5 ffffffd6 31 74 ffffffa3 ffffffb3 ffffff8b 31 ffffffc0 14 3a 57 02 fffffff5 fffffff2 ffffff8a 43 fffffff3 ffffff8b 10 74 28 53

The code works when I define buffer as:

unsigned char buffer[64];

Unfortunately I cannot then pass this unsigned char array into the next function, which requires a char array as input. I assume that this means my compiler uses signed chars.

What am I missing here? Any help would be greatly appreciated.

Phil
  • 1
  • 1

1 Answers1

1

Your architecture has char with sign. Every integer type with rank less than int is promoted to int or unsigned int when passed as a variadic function argument. Signed promotion keeps the sign. That's why you're getting 0xFFFFFF prepeneded to values over 128 (0x80).

You can fix the display problem by casting the value to unsigned char or, better yet, uint8_t:

printf("%02x", (uint8_t)buffer[i])
krzaq
  • 16,240
  • 4
  • 46
  • 61
  • The issue is that I need signed char values to input into the next function. Are the correct values being stored in the buffer and it is just a display issue? – Phil Oct 11 '16 at 02:36
  • That's why I suggest casting only for the printing function. Your data is correct, but it gets modified (as described in the answer) on the way to the standard output – krzaq Oct 11 '16 at 02:37