2017-03-01 27 views
1

我有以下功能:如何編寫短/詮釋爲1個字節的緩衝區

fun asByteArray(value: Short): ByteArray { 
    val buffer: ByteBuffer = ByteBuffer.allocate(2) 
    buffer.order(ByteOrder.BIG_ENDIAN) 
    buffer.putShort(value) 
    buffer.flip() 
    return buffer.array() 
} 

fun asByteArray(value: Int): ByteArray { 
    val buffer: ByteBuffer = ByteBuffer.allocate(4) 
    buffer.order(ByteOrder.BIG_ENDIAN) 
    buffer.putInt(value) 
    buffer.flip() 
    return buffer.array() 
} 

如果值是255,那麼我想它被寫入到1米字節的緩衝區。我該怎麼做? 如果我做ByteBuffer.allocate(1)並嘗試寫入short/int值,則發生BufferOverflowException。

+0

您的實際問題已經有了答案。你應該澄清這個問題或者提出一個新的問題來解釋你正在做的事情。 –

回答

1

不要直接寫Int,寫的value.toByte()結果:

fun asByteArray(value: Short): ByteArray { 
    val buffer: ByteBuffer = ByteBuffer.allocate(1) 
    buffer.put(value.toByte()) 
    return buffer.array() 
} 

fun asByteArray(value: Int): ByteArray { 
    val buffer: ByteBuffer = ByteBuffer.allocate(1) 
    buffer.put(value.toByte()) 
    return buffer.array() 
} 
+0

謝謝!它的工作原理,但如果我想寫Int(4字節)值「40000」到2字節緩衝區? –

+0

寫短褲怎麼樣? (40000將是一個「無符號短」,否則你不能有40000短) – Massimo

+0

是的。它是無符號短,但40000.toShort()給我-25536。是否正確buffer.putShort(40000.toShort())? –

相關問題