1

I am developing a software in Android. In a particular portion of software, I need to convert short to byte and re-convert to it to short. I tried below code but values are not same after conversion.

  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));

after executing the code values of n and n1 are not same. Why?

Lion
  • 18,729
  • 22
  • 80
  • 110
Riskhan
  • 4,434
  • 12
  • 50
  • 76

2 Answers2

5

I did not get Grahams solution to work. This, however do work:

n1 = (short)((b1 & 0xFF) | b2<<8);
Jave
  • 31,598
  • 14
  • 77
  • 90
1

You can use a 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();

edit: fixed API usage. Gah.

fge
  • 119,121
  • 33
  • 254
  • 329
  • That's an absolute overkill, the OP's question can be solved by simply using bitwise operators, as shown in @Jave's answer – Óscar López Dec 16 '11 at 12:07
  • Except this solution doesn't care about endianness! – fge Dec 16 '11 at 12:08
  • It's not a bad solution per se. If one wanted to save a large number of values or convert an array of shorts to bytes and then back, this is definitely worth considering. The simplest case - converting between one short/two bytes, as asked for, is preferably done without allocating a buffer. – Jave Dec 16 '11 at 12:45