开发者

Display ieee 32bit representation of float ... strange behaviour on pointer output

开发者 https://www.devze.com 2023-01-13 15:07 出处:网络
I have a bit of trouble with the following code: void main() { float value = 100; char * vP; vP = (char *) &value;

I have a bit of trouble with the following code:

void main()
{

float value = 100;

char * vP;

vP = (char *) &value;

printf ("%02x ", *(vP+3));
printf ("%02x ", *(vP+2));
printf ("%02x ", *(vP+1));
printf ("%02x ", *(vP+0));

}

The output I get is:

42 ffffffc8 00 00

instead of:

42 c8 00 00 (as required for an开发者_开发问答 IEEE 32bit conversion)

Can anyone help and explain what goes wrong ? If I use a float value of e.g. 12.2 everything is fine !

Thanks and best regards

Olaf.


That's because a char is signed on your machine. Then, in printf, because it's a variadic function, the char is promoted to an int keeping the negative sign. Therefore the 0xC8 becomes 0xFFFFFFC8.

Use an unsigned char* vP for force the representation to be unsigned. See http://www.ideone.com/WPQ4D for a comparison.

0

精彩评论

暂无评论...
验证码 换一张
取 消