background image

Java 基础:Java 中浮点数的存储方式

浮点数分为单精度和双精度,Java 中的单精度和双精度分别为

float

double

.你们知道

float

double

是怎么存储的吗?

  

float

4

个字节,

double

8

个字节,为了方便起见,这里就只讨论

float

类型.

  

float

其实和一个

int

型的大小是一样的,一共

32

位,第一位表示符号,

2

-

9

表示指数,后面

23

位表示小数部分.这里不多说,

  这里只举一个例子,希望能抛砖引玉,就是研究一下浮点数

0.1

的存储形式,先运行这个

程序.
  

public

 

class

 Test{

  

public

 

static

 

void

 main(String[] args) {

  

int

 x = 

0x3d800000

;

  

int

 i = 

1

 << 

22

;

  

int

 j = 

1

 << 

4

;

  

float

 f = 

0

.1f;

  

int

 y = Float.floatToIntBits(f);

  

float

 rest = f - ( (

float

1

) / j;

  

while

 (i > 

0

) {

  j <<= 

1

;

  

float

 deta = ( (

float

1

) / j;

  

if

 (rest >= deta) {

  rest -= deta;
  x |= i;
  }
  i >>= 

1

;

  }
  pr(x);
  pr(y);
  }
  

static

 

void

 pr(

int

 i) {

  System.out.println(Integer.toBinaryString(i));
  }
  }
 
  结果:
  

111101110011001100110011001101

  

111101110011001100110011001101

  程序说明:
  

int

 x=

0x3d80000

;