Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jeremy Hayden
1,740 PointsNeed help converting hex little endian to decimal
I am getting a measurement from a bluetooth device in the following format: 37 89 01 3f - This number represents 0.506 meters. This is in little endian format. That is the bytes are in reverse order and should read 3f 10 89 37. But there is more to this that I just am not grasping. Some online converters correctly convert this to 0.506, others including swift playground is converting it to 1057065271.
Is there a function that I can use in swift to convert this correctly? Clarification - 37 89 01 3f is actually sent without spaces, I just added them for readability.
Jeremy Hayden
1,740 PointsJeremy Hayden
1,740 PointsSo an update on this question. After further research I have figured out the following: The string is not a standard hex number but an IEEE 754 floating point number. I can manually calculate the number by the following:
1) The byte order needs to be reversed - so 37_89_01_3f becomes 3f_10_89_37. (Need help doing this)
2) The bytes/bits need to be converted to binary - so it becomes - 0011 1111 0000 0001 1000 1001 0011 0111 (Have not figured out how to do this yet either)
3) The binary needs to be split into 3 pieces like this - 0 01111110 00000011000100100110111
4) The first bit tells whether it is a positive or negative number
5) The second group turned back into a decimal and then subtract 127 to get your exponent in this case 126-127=-1
6) The third group represents fractions the first bit 1/2 then 1/4 then 1/8 ect.
Ok, so I can build a sloppy function to manually do this. But since IEEE 754 is an long time standard, there has to be a function already made for this. Any pushes in the right direction will be helpful.