2

I've got a quick question to someone that knows their way around C - I'm trying to save a char array using hex values, so it looks like this :

char string[84]={0x32,0x51,0x0b,0xa9,0xba,0xbe,0xbb,0xbe,0xfd,0x00,0x15,0x47,0xa8,0x10,0xe6,0x71,0x49,0xca,0xee,0x11,0xd9,0x45,0xcd,0x7f,0xc8,0x1a,0x05,0xe9,0xf8,0x5a,0xac,0x65,0x0e,0x90,0x52,0xba,0x6a,0x8c,0xd8,0x25,0x7b,0xf1,0x4d,0x13,0xe6,0xf0,0xa8,0x03,0xb5,0x4f,0xde,0x9e,0x77,0x47,0x2d,0xbf,0xf8,0x9d,0x71,0xb5,0x7b,0xdd,0xef,0x12,0x13,0x36,0xcb,0x85,0xcc,0xb8,0xf3,0x31,0x5f,0x4b,0x52,0xe3,0x01,0xd1,0x6e,0x9f,0x52,0xf9,0x04};

so basically when I output it using for example something like

for (i=0;i<string_len;i++)
        printf("%d \t---\t %x\n",i,cipher_11[i]);

I'd expect to get the same values, just without the 0x in front and it does work for most of those values, some of them however have "ffff" in front which kind of breaks the rest of my program :) Kind of a newbie in hex operations so I'm pretty sure I'm doing something very silly. Any hints ? (btw the output looks like the picture : http://postimg.org/image/k0npwh9a5/ )

1 Answer 1

5

Some of your characters have their most significant bit set, and so would represent a negative value (assuming your compiler treats char as a signed value). So when it is implicitly cast as an integer (during the call to printf), it will be interpreted as a negative value. This is the case for all values larger than 0x7f.

You should either declare cipher_11 as unsigned char, or cast the value during printf:

printf("%d \t---\t %x\n", i, (unsigned char)cipher_11[i]);
Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot for the quick reply, that does solve the issue :). I was thinking it might have something to do with negative numbers, just wasn't sure how to get around that. declaring the value as unsigned char does exactly what I want - in dev c++ at least :).

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.