TIL: Neat way to convert hex to BCD (decimal)

Recommended Posts

Often for debugging purposes in a live system I need to display internal states on a seven segment display. This is trivial when I only need to display hex numbers but recently I needed the value represented in decimal because it made more sense for my application. I had a need for a hex to dec converter and as I usually do, I google it first, in case it had been done already. Sure enough, someone has, and the solution involves only shifting and adding 3. The method involved was new to me as I hadn't heard of this way of converting hex to dec, but it works, see his blog. Hope I taught some of you something today :)


Share this post

Link to post
Share on other sites

The last bit of has how you can chain them in a a very cunning way that is even more confusing!


For some other bit twiddling magic have a look at Mostly of interest to software use, but interesting if you like that stuff... eg:


min = y ^ ((x ^ y) & -(x < y)); // min(x, y)

Or for the ultimate of bit twiddling hack (based on the quake III arena source):


float fast_inverse_square_root( float number ){        long i;        float x2, y;        const float threehalfs = 1.5F;         x2 = number * 0.5F;        y  = number;        i  = * ( long * ) &y;                       // evil floating point bit level hacking        i  = 0x5f3759df - ( i >> 1 );               // what the f#@k?        y  = * ( float * ) &i;        y  = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration               y = y * ( threehalfs - ( x2 * y * y ) );        return y;}

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now