hi all,
i want to convert array of short to array of bytes in order to send it in Datagram Packet and then convert it from bytes to short

Obviously you can use bitwize operations to separate out the two bytes of each short and store them into consecutive elements of a byte array (and vice-versa), but does anyone know a smarter solution?

Edited 1 Year Ago by JamesCherrill

could you please tell me how bitwise operation and does this operation affects the bits inside because i am dealing with audio file or tell me how i can send array of short using DatagramPacket

Use bitwize shift right 8 to leave just the first 8 bits, and put those in a byte
Use bitwize AND to mask just the last 8 bits, and put those in the next byte

reverse the process to join those 2 bytes back into a short.

Doesn't matter what the data is, that will faithfully convert a short[n] to a byte[2*n], and back again

here is the code toconvert array of short to array of byte

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

but now i want to know how to convert array of byte to array of short

thanks inadvance

Comments
Posting someone else's code without proper attribution. Lazy cheat.

Instead of copying code from the web and implying that it's yours, why not try writing some code yourself.

ps DaniWeb Member Rules include:
Do ensure you own the intellectual property rights to everything that you post.

i did not say that's my code in any way i said here is the code to convert array of short to array of byte so i did not imply it is my code , if you could help i will be thankful if not i suggest to stop giving me advice

You posted someone else's code without permission, in violation of the Member Rules. I am not advising you, I am warning you. Write yor own code, and post that.

This article has been dead for over six months. Start a new discussion instead.