Riskhan
Riskhan

Reputation: 4470

short to byte and byte to short conversion in Android

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?

Upvotes: 1

Views: 3714

Answers (2)

Jave
Jave

Reputation: 31846

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

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

Upvotes: 5

fge
fge

Reputation: 121760

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.

Upvotes: 1

Related Questions