Java short array to bytes

Convert short to byte array in Java

The following code shows how to convert short to byte array.

Example

 /*from w w w . j a v a 2 s . co m*/ import java.nio.ByteBuffer; public class Main < public static byte[] convertToByteArray(short value) < byte[] bytes = new byte[2]; ByteBuffer buffer = ByteBuffer.allocate(bytes.length); buffer.putShort(value); return buffer.array(); > public static void main(String[] argv) < System.out.println(convertToByteArray((short)213)); > > 

The code above generates the following result.

Источник

Java convert short to byte

In this Java core tutorial we learn how to convert a short value into a byte value with different solutions in Java programming language.

Table of contents

How to cast short to byte value

In this first solution to convert a short to byte value we just simple cast a short variable to a byte variable as the example Java code below.

public class ConvertShortToByteExample1  public static void main(String. args)  short shortValue = 67; byte byteValue = (byte)shortValue; System.out.println("short value: " + shortValue); System.out.println("byte value: " + byteValue); > >
short value: 67 byte value: 67

Using Short.byteValue() method

In this second solution, we use the Short.byteValue() method to return a byte value from a given Short object as the following Java code.

public class ConvertShortToByteExample2  public static void main(String. args)  Short shortValue = 69; byte byteValue = shortValue.byteValue(); System.out.println("short value: " + shortValue); System.out.println("byte value: " + byteValue); > >
short value: 69 byte value: 69

Источник

How to convert short array to byte array

I found ByteBuffer to be the slowest conversion method out of three that I’ve profiled. See below. Platform: Nexus S, Android 4.1.1, No SIM card,And just to be give as much info as possible here is the code after that uses the byte array,Here is the code leading up to the conversion

Method #1: Use a ByteBuffer

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: Twiddle bits directly

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

TypeCast.java

package mynamespace.util; public class TypeCast < public static native byte [] shortToByte(short [] input); static < System.loadLibrary("type_conversion"); >> 
#include #include jbyteArray Java_mynamespace_util_TypeCast_shortToByte(JNIEnv *env, jobject obj, jshortArray input) < jshort *input_array_elements; int input_length; jbyte *output_array_elements; jbyteArray output; input_array_elements = (*env)->GetShortArrayElements(env, input, 0); input_length = (*env)->GetArrayLength(env, input); output = (jbyteArray) ((*env)->NewByteArray(env, input_length * 2)); output_array_elements = (*env)->GetByteArrayElements(env, output, 0); memcpy(output_array_elements, input_array_elements, input_length * 2); (*env)->ReleaseShortArrayElements(env, input, input_array_elements, JNI_ABORT); (*env)->ReleaseByteArrayElements(env, output, output_array_elements, 0); return output; > 

Answer by Cal Pollard

putWrites bytes in the given byte array, starting from the specified offset, to the current position an,allocateCreates a byte buffer based on a newly allocated byte array., The new buffer shares its content with this buffer, which means either buffer’s change of content will be visible to the other. The two buffer’s position, limit and mark are independent. ,arrayReturns the byte array which this buffer is based on, if there is one.

Answer by Barrett Jenkins

If you need to convert and concatenate several values (possibly even of different types), use a shared ByteBuffer instance, or use ByteStreams.newDataOutput() to get a growable buffer., BYTES public static final int BYTES The number of bytes required to represent a primitive short value. See Also:Constant Field Values , toByteArray @GwtIncompatible(value=»doesn\’t work») public static byte[] toByteArray(short value) Returns a big-endian representation of value in a 2-element byte array; equivalent to ByteBuffer.allocate(2).putShort(value).array(). For example, the input value (short) 0x1234 would yield the byte array . If you need to convert and concatenate several values (possibly even of different types), use a shared ByteBuffer instance, or use ByteStreams.newDataOutput() to get a growable buffer. , contains public static boolean contains(short[] array, short target) Returns true if target is present as an element anywhere in array. Parameters:array — an array of short values, possibly emptytarget — a primitive short value Returns:true if array[i] == target for some value of i

@CheckReturnValue @GwtCompatible(emulated=true) public final class Shorts extends Object

Answer by Sariyah Hancock

Posted 02 May 2010 — 03:57 AM , Posted 14 May 2010 — 04:31 AM ,Parsing JSON Nested Array With GSON On Android ,Aforge.mobile On Android — Bitmap Conversions

// Allocate Recorder and Start Recording� int bufferRead = 0; int bufferSize = AudioRecord.getMinBufferSize(this.getFrequency(), this .getChannelConfiguration(), this.getAudioEncoding()); AudioRecord recordInstance = new AudioRecord( MediaRecorder.AudioSource.MIC, this.getFrequency(), this .getChannelConfiguration(), this.getAudioEncoding(), bufferSize); short[] tempBuffer = new short[bufferSize]; recordInstance.startRecording(); while (this.isRecording) < // Are we paused? synchronized (mutex) < if (this.isPaused) < try < mutex.wait(250); >catch (InterruptedException e) < throw new IllegalStateException("Wait() interrupted!", e); >continue; > > bufferRead = recordInstance.read(tempBuffer, 0, bufferSize); if (bufferRead == AudioRecord.ERROR_INVALID_OPERATION) < throw new IllegalStateException( "read() returned AudioRecord.ERROR_INVALID_OPERATION"); >else if (bufferRead == AudioRecord.ERROR_BAD_VALUE) < throw new IllegalStateException( "read() returned AudioRecord.ERROR_BAD_VALUE"); >else if (bufferRead == AudioRecord.ERROR_INVALID_OPERATION) < throw new IllegalStateException( "read() returned AudioRecord.ERROR_INVALID_OPERATION"); >try < int tempint; ByteBuffer bb = ByteBuffer.allocate(tempBuffer.length*2); bb.order(ByteOrder.LITTLE_ENDIAN); for (int idxBuffer = 0; idxBuffer < bufferRead; ++idxBuffer) < bb.putShort(idxBuffer,tempBuffer[idxBuffer]); // Log.e("maxsap","------------* COUNTER ->"+idxBuffer+" BUFFER VALUE IN SHORT -> "+ tempBuffer[idxBuffer]+" BYTEBUFFER VALUE -> "+bb.get(idxBuffer)+"*-----------"); dataOutputStreamInstance.writeByte(bb.get(idxBuffer)); > > catch (IOException e)

Answer by Cameron Merritt

In this example, the GetBytes(Int32) method of the BitConverter class is called to convert an int to an array of bytes.,This example shows you how to use the BitConverter class to convert an array of bytes to an int and back to an array of bytes. You may have to convert from bytes to a built-in data type after you read bytes off the network, for example. In addition to the ToInt32(Byte[], Int32) method in the example, the following table lists methods in the BitConverter class that convert bytes (from an array of bytes) to other built-in types.,The output may differ depending on the endianness of your computer’s architecture.,This example initializes an array of bytes, reverses the array if the computer architecture is little-endian (that is, the least significant byte is stored first), and then calls the ToInt32(Byte[], Int32) method to convert four bytes in the array to an int. The second argument to ToInt32(Byte[], Int32) specifies the start index of the array of bytes.

byte[] bytes = < 0, 0, 0, 25 >; // If the system architecture is little-endian (that is, little end first), // reverse the byte array. if (BitConverter.IsLittleEndian) Array.Reverse(bytes); int i = BitConverter.ToInt32(bytes, 0); Console.WriteLine("int: ", i); // Output: int: 25 
byte[] bytes = BitConverter.GetBytes(201805978); Console.WriteLine("byte array: " + BitConverter.ToString(bytes)); // Output: byte array: 9A-50-07-0C 

Answer by Jakobe Gibson

I have found converting a short to byte array, and byte array to short array, but not short array to byte array.,Here is the code leading up to the conversion,Java short is a 16-bit type, and byte is an 8-bit type. You have a loop that tries to insert N shorts into a buffer that’s N-bytes long; it needs to be 2*N bytes long to fit all your data.,And just to be give as much info as possible here is the code after that uses the byte array

Here is the code leading up to the conversion

 int i = 0; ByteBuffer byteBuf = ByteBuffer.allocate(N); while (buffer.length >= i) < byteBuf.putShort(buffer[i]); i++; >bytes2 = byteBuf.array(); 
 ByteBuffer.wrap(bytes2).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(buffer); 

And just to be give as much info as possible here is the code after that uses the byte array

Log.i("Map", "test"); //convert to ulaw read(bytes2, 0, N); //send to server os.write(bytes2,0,bytes2.length); System.out.println("bytesRead "+buffer.length); System.out.println("data "+Arrays.toString(buffer)); > 

Источник

Java short type conversion

The following list have the methods which we can use to convert short value.

  • byte byteValue() returns the value of this Short as a byte.
  • double doubleValue() returns the value of this Short as a double.
  • float floatValue() returns the value of this Short as a float.
  • int intValue() returns the value of this Short as an int.
  • long longValue() returns the value of this Short as a long.
  • short shortValue() returns the value of this Short as a short.

public class Main < public static void main(String[] args) < Short shortObject = new Short("10"); byte b = shortObject.byteValue(); System.out.println("byte:"+b); /*j a va2 s.c o m*/ short s = shortObject.shortValue(); System.out.println("short:"+s); int i = shortObject.intValue(); System.out.println("int:"+i); float f = shortObject.floatValue(); System.out.println("float"+f); double d = shortObject.doubleValue(); System.out.println("double:"+d); long l = shortObject.longValue(); System.out.println("long:"+l); > > 

Decode a string to short value

Short.decode(String nm) decodes a String into a Short. It accepts decimal, hexadecimal, and octal numbers given by the following grammar:

+/- 0x HexDigits +/- 0X HexDigits +/- # HexDigits +/- 0 OctalDigits 

Small demo to illustrates the decode method.

public class Main < public static void main(String[] args) < // j a va 2 s. c o m System.out.println("Decimal 10:"+Short.decode("10")); System.out.println("Octal 10:"+Short.decode("010")); System.out.println("Hex F:"+Short.decode("0XF")); System.out.println("Negative Hex F:"+Short.decode("-0XF")); > > 

Convert string to a short value

Short class has the following methods we can use to convert a string to a short type value.

  • static short parseShort(String s) parses the string argument as a signed decimal short.
  • static short parseShort(String s, int radix) parses the string argument as a signed short in the radix specified by the second argument.
  • static Short valueOf(short s) returns a Short instance representing the specified short value.
  • static Short valueOf(String s) returns a Short object holding the value given by the specified String.
  • static Short valueOf(String s, int radix) returns a Short object holding the value extracted from the specified String when parsed with the radix given by the second argument.

The following code demonstrates the methods listed above.

public class Main < public static void main(String[] args) < /*from j a va2s . c om*/ System.out.println(Short.parseShort("10")); System.out.println(Short.parseShort("10",8)); System.out.println(Short.valueOf("10")); System.out.println(Short.valueOf("10",8)); > > 

Convert short value to string

To convert short value to string we can use the following methods.

  • String toString() returns a String object representing this Short’s value.
  • static String toString(short s) returns a new String object representing the specified short.

public class Main < public static void main(String[] args) < Short shortValue = new Short("10"); System.out.println(shortValue.toString()); //from j a va 2s. c o m System.out.println(Short.toString((short)10)); > > 

Next chapter.

What you will learn in the next chapter:

Источник

Читайте также:  Немедленно вызываемые функции javascript
Оцените статью