LoginSignup
0
1

More than 3 years have passed since last update.

JAVA Convert short[] to byte[]

Posted at

Method 1:

byte [] ShortToByte_ByteBuffer_Method(short [] input)
{
  int index;
  int iterations = input.length;

  ByteBuffer bb = ByteBuffer.allocate(input.length * 2);

  for(index = 0; index != iterations; ++index)
  {
    bb.putShort(input[index]);    
  }

  return bb.array();       
}

Method 2:

byte [] ShortToByte_Twiddle_Method(short [] input)
{
  int short_index, byte_index;
  int iterations = input.length;

  byte [] buffer = new byte[input.length * 2];

  short_index = byte_index = 0;

  for(/*NOP*/; short_index != iterations; /*NOP*/)
  {
    buffer[byte_index]     = (byte) (input[short_index] & 0x00FF); 
    buffer[byte_index + 1] = (byte) ((input[short_index] & 0xFF00) >> 8);

    ++short_index; byte_index += 2;
  }

  return buffer;
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1