Convert between formats with different number of bits for exponent and fractional part

▼魔方 西西 提交于 2019-12-25 02:38:28

问题


I am trying to refresh on floats. I am reading an exercise that asks to convert from format A having: k=3, 4 bits fraction and Bias=3 to format B having k=4, 3 bits fraction and Bias 7.
We should round when necessary.
Example between formats:

011 0000 (Value = 1)      =====> 0111 000 (Value = 1)  
010 1001 (Value = 25/32)  =====> 0110 100 (Value = 3/4 Rounded down)  
110 1111 (Value = 31/2)   =====> 1011 000 (Value = 16 Rounded up)  

Problem: I can not figure out how the conversion works. First of all I managed to do it correctly in some case but my approach was to convert the bit pattern of format A to the decimal value and then to express that value in the bit pattern of format B.
But is there a way to somehow go from one bit pattern to the other without doing this conversion, just knowing that we extend the e by 1 bit and reduce the fraction by 1?


回答1:


But is there a way to somehow go from one bit pattern to the other without doing this conversion, just knowing that we extend the e by 1 bit and reduce the fraction by 1?

Yes, and this is much simpler than going through the decimal value (which is only correct if you convert to the exact decimal value and not an approximation).

011 0000 (Value = 1)   
  represents 1.0000 * 23-3
  is really 1.0 * 20 in “natural” binary
  represents 1.000 * 27-7 to pre-format for the destination format
   =====> 0111 000 (Value = 1)

Second example:

010 1001 (Value = 25/32)  
  represents 1.1001 * 22-3
  is really 1.1001 * 2-1
  rounds to 1.100 * 2-1 when we suppress one digit, because of “ties-to-even”
  is 1.100 * 26-7 pre-formated
=====> 0110 100 (Value = 3/4 Rounded down)

Third example:

110 1111 (Value = 31/2)
  represents 1.1111 * 26-3
  is really 1.1111 * 23
  rounds to 10.000 * 23 when we suppress one digit, because “ties-to-even” means “up” here and the carry propagates a long way
  renormalizes into 1.000 * 24
  is 1.000 * 211-7 pre-formated
   =====> 1011 000 (Value = 16 Rounded up) 

Examples 2 and 3 are “halfway cases”. Well, rounding from 4-bit fractions to 3-bit fractions, 50% of examples will be halfway cases anyway.

In example 2, 1.1001 is as close to 1.100 as it is to 1.101. So how is the result chosen? The one that is chosen is the one that ends with 0. Here, 1.100.



来源:https://stackoverflow.com/questions/25831471/convert-between-formats-with-different-number-of-bits-for-exponent-and-fractiona

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!