2014-11-14 120 views
0

我想切換字節緩衝區字節緩衝區,但它沒有影響。什麼做錯了? 也許我的調試主要功能不正確?字節緩衝區開關字節序

@Override 
public byte[] toBytes(BigDecimal type) { 
    int octets = getOctetsNumber(); 
    BigInteger intVal = type.unscaledValue(); 

    byte[] temp = intVal.toByteArray(); 
    int addCount = octets - temp.length; 

    //  DEBUG 
    ByteBuffer buffer = ByteBuffer.allocate(octets); 
    for(byte b: intVal.toByteArray()){ 
     buffer.put(b); 
    } 
    if (addCount > 0){ 
     for (; addCount > 0; addCount--) { 
      buffer.put((byte)0x00); 
     } 
    } 
    buffer.flip(); 

    buffer.order(ByteOrder.BIG_ENDIAN); 

    return buffer.array(); 
} 

public static void main(String[] arg) { 
    IntegerDatatype intVal = new IntegerDatatype(17); 
    BigDecimal bd = new BigDecimal(32000); 

    byte[] bytes = intVal.toBytes(bd); 
    String out = new String(); 
    for (byte b : bytes) { 
     out += Integer.toBinaryString(b & 255 | 256).substring(1) + " "; 
    } 
    System.out.println(out); 
} 

主要功能打印這個二進制字符串:01111101 00000000 00000000 00000000 但必須打印:00000000 10111110 00000000 00000000

回答

1

你需要把值到緩衝區之前改變存儲方式。 只需在分配緩衝區大小後立即移動該行,您應該沒問題。

//  DEBUG 
ByteBuffer buffer = ByteBuffer.allocate(octets); 
buffer.order(ByteOrder.BIG_ENDIAN); 
for(byte b: intVal.toByteArray()){ 
    buffer.put(b); 
} 

...

此外,字節順序不只會影響較大數值的字節順序,而不是字節解釋here

+0

謝謝邁克爾。我完全忘記了只有在緩衝區中推入多字節類型時,字節序纔會生效。 – Constantine 2014-11-14 14:41:59

相關問題