Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a byte array as shorts in Java

I have a an array of byte, size n, that really represents an array of short of size n/2. Before I write the array to a disk file I need to adjust the values by adding bias values stored in another array of short. In C++ I would just assign the address of the byte array to a pointer for a short array with a cast to short and use pointer arithmetic or use a union.

How may this be done in Java - I'm very new to Java BTW.

like image 874
Nate Lockwood Avatar asked Mar 23 '10 00:03

Nate Lockwood


People also ask

Can we convert byte to short in Java?

The shortValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as short.

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

Can we convert byte array to file in Java?

Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.

What does byte [] do in Java?

A byte array is an array of bytes (tautology FTW!). You could use a byte array to store a collection of binary data, for example, the contents of a file. The downside to this is that the entire file contents must be loaded into memory.


1 Answers

You could do the bit-twiddling yourself but I'd recommend taking a look at the ByteBuffer and ShortBuffer classes.

byte[] arr = ...
ByteBuffer bb = ByteBuffer.wrap(arr); // Wrapper around underlying byte[].
ShortBuffer sb = bb.asShortBuffer(); // Wrapper around ByteBuffer.

// Now traverse ShortBuffer to obtain each short.
short s1 = sb.get();
short s2 = sb.get(); // etc.
like image 140
Adamski Avatar answered Oct 05 '22 18:10

Adamski