Author Topic: printing decimal part of a number having the bits  (Read 2182 times)

0 Members and 1 Guest are viewing this topic.

Offline MoriambarTopic starter

  • Supporter
  • ****
  • Posts: 502
  • Country: it
printing decimal part of a number having the bits
« on: June 10, 2021, 02:41:52 pm »
Hi.
My problem is quite complex, perhaps due to my lack of skill and knowledge.

I have an attiny84 which receives a 16bit "number" which represents the mantissa (idk whether it's correct in English) of a number.
By representing I mean that bit 15 indicates the "1/2" fraction, 14 the "1/4" fraction and so on.
If this can simplify matters: I don't ever have to consider the full 16 bits, there's no harm in doing that (those that I don't have to consider will be 0), but I have the number of "significant bits".

So now my goal is to print the decimal value of that thing (print as on an i2c lcd). For example if my bits are E1 10 00 00 this should correspond to "908203125" (1/2+1/4+1/8+1/32+1/256 if I calculated correctly).

Currently I devised a method to calculate the number, except for leading zeroes, ie if I have 1/128 (=0078125) I can easily get the "78125" but it's hard to determine the number of leading zeroes.

I think then perhaps there's either a very good way to calculate the mantissa or some "general" way to calculate my leading zeroes, giving the number of bits (without hardcoding them).

Can anyone please help? I'll try and give as much info as I can.
Cheers
 

Offline oPossum

  • Super Contributor
  • ***
  • Posts: 1453
  • Country: us
  • Very dangerous - may attack at any time
Re: printing decimal part of a number having the bits
« Reply #1 on: June 10, 2021, 03:18:07 pm »
Code: [Select]
uint32_t x = 0xE110;
printf("0.");
do printf("%c", ((x *= 10) >> 16) + '0'); while (x &= 0xFFFF);
 
The following users thanked this post: Moriambar

Offline MoriambarTopic starter

  • Supporter
  • ****
  • Posts: 502
  • Country: it
Re: printing decimal part of a number having the bits
« Reply #2 on: June 10, 2021, 04:13:55 pm »
Code: [Select]
uint32_t x = 0xE110;
printf("0.");
do printf("%c", ((x *= 10) >> 16) + '0'); while (x &= 0xFFFF);

Cool I adapted this to my specifics and it works like a charm. It also made me find some bugs in my reasonings. Thanks!!
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf