I am trying to convert a float value to a 4-byte hexadecimal value.
For example my input is: 58.5. My expected output is: 426A0000 or like 0x42 0x6A 0x00 0x00.
My program is:
void setup() {
Serial.begin(9600);
float z = 128;
unsigned i;
unsigned char *chpt;
chpt = (unsigned char *)&z;
Serial.print("Float Value : ");
Serial.println(z);
Serial.print("4 Byte hexadecimal Value: ");
for (i = 0; i < sizeof(z); i++) {
Serial.print(chpt[i],HEX);
//Serial.print(" ");
}
Serial.println();
}
void loop() {
}
My current output is:
Float Value : 128.00
4 Byte hexadecimal Value: 00043
1 Answer 1
This value looks pretty correct to me. It is stored in little endian thou.
0x43000000 is the actual value.
Serial.print(x, HEX)
truncates leading zeros. so 00
gets 0
So your output is 0 0 0 43
which corresponds to the little endian representation of the above.
Make yourself familiar with the floating point representation IEEE-754.
Also try the online FoatConverter.
Try the following:
char floatString[9];
sprintf(floatString, "%02X%02X%02x%02x", chpt[3], chpt[2], chpt[1], chpt[0]);
floatString[8] = '0円';
Serial.print(floatString);
-
Thanks for the reply @kwasmich If I input the float value say Float Value : 235.56 I am getting values like this. 4 Byte hexadecimal Value: 5C8F6B43 Any changes in the program that you would like to suggest to obtain the result as 436B8F5CJosh Earnest– Josh Earnest2019年12月04日 08:14:02 +00:00Commented Dec 4, 2019 at 8:14
-
I just added some sample code that should give you what you wanted in the first place.Kwasmich– Kwasmich2019年12月04日 08:15:23 +00:00Commented Dec 4, 2019 at 8:15
-
printf is a powerful tool.
%02X
means, print the value as hex (x) with at least 2 places width (2), padded with zeros(0).Kwasmich– Kwasmich2019年12月04日 08:17:50 +00:00Commented Dec 4, 2019 at 8:17 -
Thanks a lot!!!!!!!!!!!!! I as able to get my output. But then I am manually entering the float values. What should I change in the program so as to input a float value from Serial monitor and get the output in serial monitor?Josh Earnest– Josh Earnest2019年12月04日 08:27:10 +00:00Commented Dec 4, 2019 at 8:27
-
I don't have a ready made solution for that. But the steps would be similar but in reverse. Use
String string = Serial.readString();
to obtain the entire string in one block. Usesscanf(string.c_str, "%02X%02X%02X%02X", &chpt[3], &chpt[2], &chpt[1], &chpt[0]);
to transfer the read hex values into the byte array. Something like that.Kwasmich– Kwasmich2019年12月04日 08:33:33 +00:00Commented Dec 4, 2019 at 8:33