I want to convert float value to hex value and required the sum of all bits.
Computers use binary mathematics. To compute the sum of the bits representing a floating point number, simply add up those bits.
"Hex" is a human readable representation of a binary number, like decimal but with 16 as the number base.
Serial.begin(9600);
float f = 58.5;
Serial.print("0x");
Serial.println((uint32_t)&f, HEX);
Output 0x426A0000.
I want to Add 42+6A
...and that's why you use code tags for posting code.
(What's stopping you adding those four bytes together?)
This does not convert a float to hex, it converts the address of variable f to an integer and prints it.
No, the asterisk is there,but the lack of code tags converted it to italics
Oh, I see.
In that case, the snippet invokes undefined behaviour because of the strict aliasing rules.
sorry but add 42+6A+00+00
Yes, that's right.
The following, very icky, method should work:
float f {58.5};
uint32_t sum {0};
for (size_t i {0}; i < sizeof(float); ++i) {
sum += reinterpret_cast<uint8_t const* const>(&f)[i];
}
Serial.println(sum); // Prints "172".
[edit]
If you want to have something that works for other types as well, you could consider the following:
template <class T> uint32_t byteSum(T const& data) {
uint32_t sum {0};
for (size_t i {0}; i < sizeof(T); ++i) {
sum += reinterpret_cast<uint8_t const* const>(&data)[i];
}
return sum;
}
Usage:
Serial.println(byteSum(f)); // Prints "172";
something like this..
uint8_t* b = (uint8_t *)&f;
uint16_t sum;
for (int i = 0; i < sizeof(float); i++) {
sum += *b;
b++;
}
good luck.. ~q
Something like this:
void setup()
{
Serial.begin(9600);
float y = 58.5;
byte *ptr;
ptr = (byte*)&y;
uint16_t sum = 0;
for(int i = 0; i< 4; i++, ptr++)
{
sum += *ptr;
}
Serial.println(sum, HEX); //shows: AC
//---for manual verification-----
float y1 = 58.5;
long *ptr1;
ptr1 = (long*)&y1;
long m = *ptr1;
Serial.println(m, HEX); //show: 426A0000
}
void loop()
{
}
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.