在Java中将short转换为byte [] [英] Convert short to byte[] in Java

查看:2650
本文介绍了在Java中将short转换为byte []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 short (2个字节)转换为Java中的字节数组,例如

How can I convert a short (2 bytes) to a byte array in Java, e.g.

short x = 233;
byte[] ret = new byte[2];

...

它应该是这样的。但不确定。

it should be something like this. But not sure.

((0xFF << 8) & x) >> 0;

编辑:

您也可以使用:

java.nio.ByteOrder.nativeOrder();

发现获取本机位顺序是大还是小。此外,以下代码取自 java.io.Bits ,其中包含:

To discover to get whether the native bit order is big or small. In addition the following code is taken from java.io.Bits which does:


  • byte(array / offset)to boolean

  • byte array to char

  • byte array to short

  • byte array to int

  • byte array to float

  • byte array to long

  • byte array to double

  • byte (array/offset) to boolean
  • byte array to char
  • byte array to short
  • byte array to int
  • byte array to float
  • byte array to long
  • byte array to double

反之亦然。

推荐答案

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

这篇关于在Java中将short转换为byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆