2011-05-17 56 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); 
        } 
      }