Tuesday 21 April 2009

Thank the stars for the STL

The C++ Standard Template Library is something which I've been taking for granted lately but every once in a while something happens that makes you stand back and appreciate the functionality it provides. Today was one of those days.

For reasons I'll not go into I encountered the situation today where I needed to take a hexadecimal value representing a 32 bit value and convert that into an IEEE 754 type single precision value. Fortunately after some looking around I found the entry on wikipedia which explained how a single precision value is represented in a 32bit binary value, at that point however I was having nightmares about bit shifting and XOR'ing with values to determine which bits were set!

Enter the STL, which allowed me to implement a solution which although maybe not as compact or efficient as other methods is at least easy to follow and maintain/comment. And it was all thanks to the bitset class which takes an unsigned long and represents it as an array of bits. From this point it becomes trivial to determine the sign bit, the 8 exponent bits and the 23 (plus 1 implicit) mantissa bits. So after a little reading and some coding I ended up with a method which reliably transforms hexadecimal strings (i.e. DEADBEEF) into single precision values.

Maybe not the most interesting of posts but I felt the need to share :)

No comments:

Post a Comment

Note: only a member of this blog may post a comment.