On your machine, char
is signed by default. Change the type to unsigned char
and you'll get the results you are expecting.
A Quick explanation on why this is
In computer systems, the MSB (Most Significant Bit) is the bit with the highest value (the left most bit). The MSB of a number is used to determine if the number is positive or negative. Even though a char
type is 8-bits long, a signed char
only can use 7-bits because the 8th bit determines if its positive or negative. Here is an example:
Data Type: signed char
Decimal: 25
Binary: 00011001
^
|
--- Signed flag. 0 indicates positive number. 1 indicates negtive number
Because a signed char
uses the 8th bit as a signed flag, the number of bits it can actually use to store a number is 7-bits. The largest value you can store in 7-bits is 127 (7F
in hex).
In order to convert a number from positive to negative, computers use something called two's-compliment. How it works is that all the bits are inverted, then 1
is added to the value. Here's an example:
Decimal: 25
Binary: 00011001
Decimal: -25
Binary: 11100111
When you declared char testStream[8]
, the compiler assumed you wanted signed char
's. When you assigned a value of 0x9D
or 0xF3
, those numbers were bigger then 0x7F
, which is the biggest number that can fit into 7-bits of a signed char. Therefore, when you tried to printf
the value to the screen, it was expanded into an int
and filled with FF
's.
I hope this explanation clears things up!