您的位置:首页 > 编程语言 > Java开发

Convert short to byte[] in Java

2015-12-24 11:43 666 查看
(转载)http://stackoverflow.com/questions/2188660/convert-short-to-byte-in-java

方法(1):

ret[0] = (byte)(x & 0xff);
ret[1] = (byte)((x >> 8) & 0xff);


方法(2):

A cleaner, albeit far less efficient solution is:
ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putShort(value);
return buffer.array();


Keep this in mind when you have to do more complex byte transformations in the future. ByteBuffers are very powerful.

//---------------------------------------------------------------------------------------------------------------------------------

总结:这里可以看到使用传统的方法就是移位取值。

还可以看到使用比较新的方案ByteBuffer来做,这个ByteBuffer不仅仅可以很方便的实现short转化为

byte[],还可以很方便的实现int转化为byte[]等等。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: