2011-05-17 59 views
4

如何从浮点数得到字节[]?我需要创建消息,其中数据我有四个字节,数据可以是无符号整型(它很容易从int获取byte []),二进制和浮点数(但我不知道如何从float获得四个字节)。任何解决方案如何从浮点数得到字节[]

回答

1

如果你认为它很容易得到一个int的字节,Float.floatToIntBits可能是你想要什么:

float f = ...; 
int i = Float.floatToIntBits(f); 
byte[] floatBytes = toBytes(i); 
14

您可以使用Float.floatToRawIntBits(float)但我怀疑你不需要的byte [],而是想成为能够写入一个字节流。在这种情况下,如果使用NIO,我会用DataOutputStream.writeFloat(float)

,您可以使用ByteBuffer.putFloat()字节缓冲区的一个好处是,你可以用ByteBuffer.order指定字节顺序(),所以你可以处理任何一种或大或小尾数。

+2

+1,这是一个能在数据写入彩车的最佳解决方案连接。 – funkybro 2011-05-17 07:22:35

9

java.lang.Float有方法floatToIntBits()floatToRawIntBits(),你可以用它来获得在的float(作为int)的位模式。所以,你可以做这样的事情:

float value = 1.5e-3f; 

int bits = Float.floatToIntBits(value); 
byte[] bytes = new byte[4]; 
bytes[0] = (byte)(bits & 0xff); 
bytes[1] = (byte)((bits >> 8) & 0xff); 
bytes[2] = (byte)((bits >> 16) & 0xff); 
bytes[3] = (byte)((bits >> 24) & 0xff); 

注:你得找出你的具体应用,其中floatToIntBits()floatToRawIntBits()是适当的,你必须确定在哪个命令你所需要的字节(小或大端)。

3

没有任何涉及数学,你可以做到这一点通过DataOutputStream写值,然后获取输出结果:

ByteArrayOutputStream bos = new ByteArrayOutputStream(4); 
DataOutputStream dos = new DataOutputStream(bos); 
dos.writeFloat(yourFloat); 
byte[] bytes = bos.toByteArray(); 
// at this point, your bytes will contain the 4-byte representation of the float. 
1
public static void main(String[] args) 
      { 
       float f = 23f; 
       byte[] op = new byte[4]; 
       int fi = Float.floatToIntBits(f); 
       for (int i = 0; i < 4; i++) 
        { 
         int offset = (op.length - 1 - i) * 8; 
         op[i] = (byte) ((fi >>> offset) & 0xff); 
        } 
       for(byte b : op) 
        { 
         System.out.format("0x%02X ", b); 
        } 
      }