How can I access a byte array as shorts in Java - 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.

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.

You can wrap your byte array with java.nio.ByteBuffer.
byte[] bytes = ...
ByteBuffer buffer = ByteBuffer.wrap( bytes );
// you may or may not need to do this
//buffer.order( ByteOrder.BIG/LITTLE_ENDIAN );
ShortBuffer shorts = buffer.asShortBuffer( );
for ( int i = 0, n=shorts.remaining( ); i < n; ++i ) {
final int index = shorts.position( ) + i;
// Perform your transformation
final short adjusted_val = shortAdjuster( shorts.get( index ) );
// Put value at the same index
shorts.put( index, adjusted_val );
}
// bytes now contains adjusted short values

The correct way to do this is using shifts. So
for (int i = 0; i < shorts.length; i++) {
shorts[i] = (short)((bytes[2*i] << 8) | bytes[2*i + 1]);
}
Also, it depends on the endian-ness of the stream in many respects. This may work better

Related

int array to byte array with one integer per byte

All related questions I've found here on SO describe the conversion between a byte array and an int array where 4 bytes are converted to a single integer and vice versa.
What I am looking for instead is converting each integer to a single byte and vice versa, knowing that none of the values of the integer array exceeds the range of an unsigned byte.
Is there a library that does that (preferably Guava or Apache commons)? Essentially, I am looking for something like this:
int[] -> byte[]
for (int i = 0; i < intArray.length; i++){
byteArray[i] = (byte) intArray[i];
}
byte[] -> int[]
for (int i = 0; i < byteArray.length; i++){
intArray[i] = 0xff & byteArray[i];
}
You cannot cast arrays in Java in that way. AFAIK, the VM just does not let you reinterpret the bytes in an array as a different type. I assume that you could use some platform-dependent JNI magic to make it so, but that would be extremely hacky.
Edit (removed sample code; added following)
If you are going to reinterpret the same bytes as different primitive types, use a ByteBuffer.
Once declared, you get direct access operations to reinterpreted bytes, such as
myByteBuffer.getInt(1); // reads bytes 4, 5, 6, 7 as an int
myByteBuffer.getByte(5); // reads byte 5 as a byte
You can also extract primitive arrays from there, but there will be extra allocations involved.
Try:
int number = 54353, divisor = 256;
byte[] byteArray = new byte[4];
byteArray[3] = number%divisor;
number = number/divisor
byteArray[2] = number%divisor;
number = number/divisor
byteArray[1] = number%divisor;
number = number/divisor
byteArray[0] = number;

Converting ints and strings into byte array and the reverse

I would like to convert some ints and some strings into a single byte array and then back again. I've done a bit of research on how to do converting, but I'm not sure if its all correct.
Converting a string to a byte array is easy:
byte[] bytes = string.getBytes();
Converting it back again via Arrays.toString() because that just creates a string of the bytes.
Does this work: String s = new String(bytes);?
Converting ints to byte array is like this:
int[] data = { int1, int2, int3 };
ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 4);
IntBuffer intBuffer = byteBuffer.asIntBuffer();
intBuffer.put(data);
byte[] my_app_state = byteBuffer.array();
But I don't know how to convert it back again.
My aim is to have say 4 ints and 2 strings converted to a single byte array and then convert them back again.
For example. I have these objects and would like them to converted to the same byte array.
int int1 = 1;
int int2 = 2;
int int3 = 3;
int int4 = 4;
String s1 = "mystring1"
String s2 = "mystring2"
Update: Removed code where I thought there was a problem. There wasn't.
For each operation, you need to determine the reverse operation, not just any operation which returns the right type. for example, the reverse of n * 2 is m / 2 not m - 2 even though the type is right.
Arrays.toString("Hi".getBytes()) => "{ 72, 105 }"
So you can do
text.getBytes() => new String(bytes) // if the same character encoding is used.
a better option is
text.getBytes("UTF-8") => new String(bytes, "UTF-8");
The problem with an array is you have two pieces of information a length and some bytes If you just write the bytes, you no longer know the length and so you can't easily decode it (perhaps impossible)
In your case, the simplest option is to use a Data Stream
// buffer which grows as needed.
ByteArrayOutputStream boas = new ByteArrayOutputStream();
// supports basic data types
DataOutputStream dos = new DataOutputStream(baos);
dos.writeInt(data.length);
for(int i: data) dow.writeInt(i);
// write the length of the string + the UTF-8 encoding of the text.
dos.writeUTF(s1);
dos.writeUTF(s2);
byte[] bytes = bytes.toByteArray();
To do the reverse, you use the InputStream and the readXxxx instead of writeXxxx methods.
Java makes it very simple to achieve this, as this is a very common use case. What you need looks very much like Serialization.
Serialization works like this: A single object can be converted to a set of bytes and stored in a byte array (usually for writing to a file or sending over a network).
The good things is that any object can become serializable by just implementing a marker interface (just 1 line of code). Also, all Wrapper datatypes and String and Collections objects like ArrayList are serializable.
Coming to your question: Put all your data in a single object and serialize that object. 3 options come to my mind:
1. An Object[] or ArrayList (if you know the order for sure, so that you can access based on position)
2. A HashMap, (if you can assign a name to each of them instead of relying on position)
3. Create your own data type with fields like int1, int2 or even more meaningful names. (Your class should implement Serializable).
Now, all your data is added into a single object. Convert this one object to a byte array and your job is done.
Check this link for how to convert a single object to byte array:
Java Serializable Object to Byte Array
Object[] payload = new Object[]{int1, int2, int3, int4, string1, string2};
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(payload);
byte[] result = out.toByteArray(); //Done
for store Strings as well you have to use some thing like
IntBuffer intBuffer = byteBuffer.asIntBuffer();
CharBuffer stringBuffer = byteBuffer.asCharBuffer();
then you have to traverse the loop on char[][] string = {s1.toCharArray(),s2.toCharArray()};
to put the each character in stringBuffer and more thing you have to do is you to make your byteBuffer to sufficient to hold these values my friend

Efficiently convert Java string into null-terminated byte[] representing a C string? (ASCII)

I would like to transform a Java String str into byte[] b with the following characteristics:
b is a valid C string (ie it has b.length = str.length() + 1 and b[str.length()] == 0.
the characters in b are obtained by converting the characters in str to 8-bit ASCII characters.
What is the most efficient way to do this — preferably an existing library function? Sadly, str.getBytes("ISO-8859-1") doesn't meet my first requirement...
// do this once to setup
CharsetEncoder enc = Charset.forName("ISO-8859-1").newEncoder();
// for each string
int len = str.length();
byte b[] = new byte[len + 1];
ByteBuffer bbuf = ByteBuffer.wrap(b);
enc.encode(CharBuffer.wrap(str), bbuf, true);
// you might want to ensure that bbuf.position() == len
b[len] = 0;
This requires allocating a couple of wrapper objects, but does not copy the string characters twice.
You can use str.getBytes("ISO-8859-1") with a little trick at the end:
byte[] stringBytes=str.getBytes("ISO-8859-1");
byte[] ntBytes=new byte[stringBytes.length+1];
System.arraycopy(stringBytes, 0, ntBytes, 0, stringBytes.length);
arraycopy is relatively fast as it can use native tricks and optimizations in many cases. The new array is filled with null bytes everywhere we didn't overwrite it(basically just the last byte).
ntBytes is the array you need.

Get single bytes from multi-byte variable in java

How can I split a variable into single bytes in java? I have for example following snippet in C++:
unsigned long someVar;
byte *p = (byte*)(void*) someVar; // byte being typedef unsigned char (from 0 to 255)
byte *bytes = new byte[sizeof(someVar)];
for(byte i = 0;i<sizeof(someVar);i++)
{
bytes[i] = *p++;
}
.... //do something with bytes
I want to accomplish the same under java, but I can't seem to find an obvious workaround.
There are two ways to do it with the ByteBuffer class. One is to create a new byte array dynamically.
long value = 123;
byte[] bytes = ByteBuffer.allocate(8).putLong(value).array();
Another is to write to an existing array.
long value = 123;
byte[] bytes = new byte[8];
ByteBuffer.wrap(bytes).putLong(value);
// bytes now contains the byte representation of 123.
If you use Guava, there is a convenience Longs.toByteArray. It is simply a wrapper for John's ByteBuffer answer above, but if you already use Guava, it's slightly "nicer" to read.

Convert Bytes to bits

I'm working with java.
I have a byte array (8 bits in each position of the array) and what I need to do is to put together 2 of the values of the array and get a value.
I'll try to explain myself better; I'm extracting audio data from a audio file. This data is stored in a byte array. Each audio sample has a size of 16 bits. If the array is:
byte[] audioData;
What I need is to get 1 value from samples audioData[0] and audioData[1] in order to get 1 audio sample.
Can anyone explain me how to do this?
Thanks in advance.
I'm not a Java developer so this could be completely off-base, but have you considered using a ByteBuffer?
Assume the LSB is at data[0]
int val;
val = (((int)data[0]) & 0x00FF) | ((int)data[1]<<8);
As suggested before, Java has classes to help you with this. You can wrap your array with a ByteBuffer and then get an IntBuffer view of it.
ByteBuffer bb = ByteBuffer.wrap(audioData);
// optional: bb.order(ByteOrder.BIG_ENDIAN) or bb.order(ByteOrder.LITTLE_ENDIAN)
IntBuffer ib = bb.asIntBuffer();
int firstInt = ib.get(0);
ByteInputStream b = new ByteInputStream(audioData);
DataInputStream data = new DataInputStream(b);
short value = data.readShort();
The advantage of the above code is that you can keep reading the rest of 'data' in the same way.
A simpler solution for just two values might be:
short value = (short) ((audioData[0]<<8) | (audioData[1] & 0xff));
This simple solution extracts two bytes, and pieces them together with the first byte being the higher order bits and the second byte the lower order bits (this is known as Big-Endian; if your byte array contained Little-Endian data, you would shift the second byte over instead for 16-bit numbers; for Little-Endian 32-bit numbers, you would have to reverse the order of all 4 bytes, because Java's integers follow Big-Endian ordering).
easier way in Java to parse an array of bytes to bits is JBBP usage
class Parsed { #Bin(type = BinType.BIT_ARRAY) byte [] bits;}
final Parsed parsed = JBBPParser.prepare("bit:1 [_] bits;").parse(theByteArray).mapTo(Parsed.class);
the code will place parsed bits of each byte as 8 bytes in the bits array of the Parsed class instance
You can convert to a short (2 bytes) by logical or-ing the two bytes together:
short value = ((short) audioData[0]) | ((short) audioData[1] << 8);
I suggest you take a look at Preon. In Preon, you would be able to say something like this:
class Sample {
#BoundNumber(size="16") // Size of the sample in bits
int value;
}
class AudioFile {
#BoundList(size="...") // Number of samples
Sample[] samples;
}
byte[] buffer = ...;
Codec<AudioFile> codec = Codecs.create(AudioFile.class);
AudioFile audioFile = codec.decode(buffer);
You can do it like this, no libraries or external classes.
byte myByte = (byte) -128;
for(int i = 0 ; i < 8 ; i++) {
boolean val = (myByte & 256) > 0;
myByte = (byte) (myByte << 1);
System.out.print(val ? 1 : 0);
}
System.out.println();
byte myByte = 0x5B;
boolean bits = new boolean[8];
for(int i = 0 ; i < 8 ; i++)
bit[i] = (myByte%2 == 1);
The results is an array of zeros and ones where 1=TRUE and 0=FALSE :)

Categories

Resources