Java Android中的短到字节和字节到短转换

Java Android中的短到字节和字节到短转换,java,android,Java,Android,我正在用Android开发一个软件。在软件的特定部分中,我需要将short转换为byte,然后再将其转换为short。我尝试了下面的代码,但转换后的值不一样 short n, n1; byte b1, b2; n = 1200; // short to bytes conversion b1 = (byte)(n & 0x00ff); b2 = (byte)((n >> 8) & 0x00ff); // bytes to short co

我正在用Android开发一个软件。在软件的特定部分中,我需要将short转换为byte,然后再将其转换为short。我尝试了下面的代码,但转换后的值不一样

  short n, n1;
  byte b1, b2;
  n = 1200;
  // short to bytes conversion
  b1 = (byte)(n & 0x00ff);
  b2 = (byte)((n >> 8) & 0x00ff);

  // bytes to short conversion
  short n1 = (short)((short)(b1) | (short)(b2 << 8));
短n,n1;
字节b1,b2;
n=1200;
//短到字节转换
b1=(字节)(n&0x00ff);
b2=(字节)((n>>8)和0x00ff);
//字节到短转换

short n1=(short)(short)(b1)|(short)(b2您可以使用ByteBuffer:

final ByteBuffer buf = ByteBuffer.allocate(2);
buf.put(shortValue);
buf.position(0);

// Read back bytes
final byte b1 = buf.get();
final byte b2 = buf.get();

// Put them back...
buf.position(0);
buf.put(b1);
buf.put(b2);

// ... Read back a short
buf.position(0);
final short newShort = buf.getShort();

编辑:修复API用法。Gah。

您可以使用ByteBuffer:

final ByteBuffer buf = ByteBuffer.allocate(2);
buf.put(shortValue);
buf.position(0);

// Read back bytes
final byte b1 = buf.get();
final byte b2 = buf.get();

// Put them back...
buf.position(0);
buf.put(b1);
buf.put(b2);

// ... Read back a short
buf.position(0);
final short newShort = buf.getShort();

编辑:修复了API用法。Gah。

我没有让Grahams解决方案工作。但是,这确实有效:

n1 = (short)((b1 & 0xFF) | b2<<8);

n1=(短)((b1&0xFF)| b2我没有让Grahams解决方案起作用。但是,这确实起作用:

n1 = (short)((b1 & 0xFF) | b2<<8);

n1=(短)((b1和0xFF)| b2Duplicate of Duplicate of the Duplicate of the Duplicate of the It’s absolute overkill,OP的问题可以通过简单地使用位运算符来解决,如@Jave的回答所示,除了这个解决方案不关心endianness!这本身不是一个坏的解决方案。如果一个人想要保存大量值或将一个短数组转换为字节,然后再返回,这就是defi非常值得考虑。最简单的情况是,按照要求在一个短字节/两个字节之间进行转换,最好是在不分配缓冲区的情况下完成。这是一个绝对的过度使用,OP的问题可以通过简单地使用位运算符来解决,如@Jave的回答所示,除了此解决方案不关心endianness!这不是一个糟糕的解决方案e、 如果要保存大量值或将短数组转换为字节,然后再转换回来,这绝对值得考虑。最简单的情况是,按照要求在一个短字节/两个字节之间进行转换,最好不用分配缓冲区。