When casting a -negative float value to unsigned long sometimes I get zero, but sometimes I get the negative float binary representation interpreted as a unsigned long. Either of these behaviors seems reasonable, but I can't figure why it gives different behaviors on some floats. In the code below I get the float 2508.0 three ways U, V, W:
- using a for loop to accumulate 15 sums of 167.2 (i.e., 15*167.2=2508). [U]
- set directly. [V=2508.0;]
- set the hex representation to be the same as 1. [W=(float)0x451CBFFF;]
If I cast the negative of the first one to unsigned long I get 0xFFFFF635. The other two give 0x0. The sum and setting directly give different hex representations, which is why I did the 3rd test. The fact that their hex representation is different makes sense because of round off, but why do two variables with the same hex representation get converted differently is hard to understand. Any explanations would be appreciated.
To get the hex representation I used:
Serial.print(*((unsigned long*)&U),HEX);
Here is the code to reproduce:
void setup() {
Serial.begin(9600);
float U=0,V=0,W=0;
for (int n = 0; n < 15; n++) {
U += 167.2;
}
V=2508.0; // 15*167.2
unsigned long tmp=0x451CBFFF; // same hex rep of U
W=*((float*)&tmp);
Serial.print(*((unsigned long*)&U),HEX);
Serial.println(" [sum]");
Serial.print(*((unsigned long*)&V),HEX);
Serial.println(" [2508.0]");
Serial.print(*((unsigned long*)&W),HEX);
Serial.println(" [same hex rep]");
Serial.println("==================(long)[-U,-V,-W]==================");
Serial.println((long)(-U),HEX);
Serial.println((long)(-V),HEX);
Serial.println((long)(-W),HEX);
Serial.println("=============(unsigned long)[-U,-V,-W]==============");
Serial.println((unsigned long)(-U),HEX);
Serial.println((unsigned long)(-V),HEX);
Serial.println((unsigned long)(-W),HEX);
}
void loop() {
}
Here is the output:
451CBFFF [sum]
451CC000 [2508.0]
451CBFFF [same hex rep]
==================(long)[-U,-V,-W]==================
FFFFF635
FFFFF634
FFFFF635
=============(unsigned long)[-U,-V,-W]==============
FFFFF635
0
0