This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
byte array to short array and back again in java
the encodeAudio() method in Xuggler has the following parameters:
int streamIndes
short[] samples
long timeStamp
TimeUnit unit
Using TargetDataLine from javax.sound.sampled I can read the data into a byte[] array
byte[] tempBuffer = new byte[10000];
fromMic.read(tempBuffer,0,tempBuffer.length);
But the problem is that the samples argument needs short[]
You are lucky enough that byte is "fully castable" to short, so:
// Grab size of the byte array, create an array of shorts of the same size
int size = byteArray.length;
short[] shortArray = new short[size];
for (int index = 0; index < size; index++)
shortArray[index] = (short) byteArray[index];
And then use shortArray.
Note: as far as primitive type goes, Java always treats them in big endian order, so converting, say, byte ff will yield short 00ff.
Related
This question already has answers here:
Convert a string representation of a hex dump to a byte array using Java?
(25 answers)
Closed 8 years ago.
I have a string which I want to cast to a byte array, however, my string is the actually representation of an image byte array (eg. String x = "00123589504e47..."). So, I'm stuck because doing x.getBytes(); doesn't do the job.. I need a way to cast the string to byte array and then save that byte array to an image in a specific directory. How can I cast it?
doing x.getBytes(); doesn't do the job
Yes, that's normal...
A char and a byte have no relationship to one another; you cannot seamlessly cast from one to the other and expect to obtain a sane result. Read about character codings.
From what you want, it appears that the String is in fact a "hex dump" of the image. You therefore need to read two chars by two chars and convert that to a byte array.
How? Well, you have hints. First, the length of the resulting byte array will always be that of the string divided by 2, so you can do that to start with:
// input is the string
final int arrayLen = input.length() / 2;
final byte[] result = new byte[arrayLen];
Then you need to walk through the string's characters and parse those two characters into a byte, and add that to the array:
int strIndex;
char[] chars = new char[2];
for (int arrayIndex = 0; arrayIndex < arrayLen; arrayIndex++) {
strIndex = 2 * arrayIndex;
chars[0] = input.charAt(strIndex);
chars[1] = input.charAt(strIndex + 1);
result[arrayIndex] = Byte.parseByte(new String(chars), 16);
}
// Done
return result;
I always use this one liner:
byte[] data = DatatypeConverter.parseHexBinary(x);
You can then instantiate a FileOutputStream for the image and write the bytes onto that.
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;
I'm parsing a byte array which contains variables of different types. I'm getting this array from HID connected to my phone. Array was made by C programmer. I'm trying to parse it using ByteBuffer class:
byte[] buffer = new byte[64];
if(connection.bulkTransfer(endpoint, buffer, 64, 1000) >= 0)
{
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
char mId = byteBuffer.getChar();
short rId = byteBuffer.getShort();
// ............................
}
But the values of this variables are not correct. Can anyone please tell me what i'm doing wrong?
There are systems with LitteEndian Byte order and BigEndian.
java uses BigEndian.
If the c programmer wrote the byte array in Little endian, you could use DataInputStream based on an Appache LittleEndianInputStream:
LittleEndianInputStream leis = new LittleEndianInputStream(is);
DataInputStream dis = new DataInputStream(leis);
int i1 = dis.readInt();
short s2 = dis.readShort();
If you and your colleague define a binary interface (file, or byte array) you always should force a speciifc byte order (Either little or big endian).
If byte order (little vs big endian) is the issue, you can set the byte order for the ByteBuffer to native without changing all of the program:
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
byteBuffer.order(ByteOrder.nativeOrder()); // Set native byte order
char mId = byteBuffer.getChar();
short rId = byteBuffer.getShort();
On the other hand, if you find ByteBuffer objects more convenient than byte arrays, tell the C programmer to return you a direct byte buffer instead of an array: easier for all parties and probably more efficient.
In past I haven't done much of byte shifting so I'm a bit loss here. Basically I have double array of size 26 and I should send the array in one UDP packet in Java. I found some examples of how to convert one double to bytearray, but I'm not sure how to apply it to double-array.
So how this should be done? Loop through the double array and convert each double and somehow concatenating them to one bytearray?
Convert your doubles into a byte array using java.nio.ByteBuffer
ByteBuffer bb = ByteBuffer.allocate(doubles.length * 8);
for(double d : doubles) {
bb.putDouble(d);
}
get the byte array
byte[] bytearray = bb.array();
send it over the net and then convert it to double array on the receiving side
ByteBuffer bb = ByteBuffer.wrap(bytearray);
double[] doubles = new double(bytearray.length / 8);
for(int i = 0; i < doubles.length; i++) {
doubles[i] = bb.getDouble();
}
So how this should be done? Loop through the double array and convert each double and somehow concatenating them to one bytearray?
Exactly. You can make use of DoubleBuffer, perhaps. (Marko linked it in his comment)
What Marko referred to was having actually a ByteBuffer and fetching a "DoubleBuffer"-View to it. So you can put the Doubles into the DoubleBuffer View and fetch the byte[] from the original ByteBuffer.
apache httpcore provides a org.apache.http.util.ByteArrayBuffer class which my be helpful
ByteArrayBuffer buffer = new ByteArrayBuffer(26);
buffer.append(...)
This question already has answers here:
how to convert short array to byte array
(3 answers)
Closed 9 years ago.
I am working with audio, I saved audio data on short array. I want to convert it to a byte array to store the wav file. I don't know convert short[] to byte[]. Can you help me.
Thank you very much.
short is 16 bit type and byte is 8 bit type . So from a n length short array you will get a 2n length byte array.
The Basics
before converting an array thing about converting a single short to byte. so as per above line you will create 2 byte from a single short.
The principle will be store first 8 bits two a byte and store second 8 bits to another short. The code will be like this
byte b1, b2;
short s;
b1 = s & 0xff;
b2 = (s >> 8) & 0xff;
Now Array
use the above principal for array now. say the array size of short is n. let the short is s
byte result[2*n];
for(int i = 0; i<2*n ; i=i+2){
b[i] = s[i>>1] & 0xff;
b[i+1] = (s[i>>1 | 1] >> 8) & 0xff;
}
Using ByteBuffer class
you can also convert short array to bytearray using ByteBuffer class.
ByteBuffer byteBuf = ByteBuffer.allocate(2*n);
for(int i = 0; i<n ; i++) {
byteBuf.putShort(buffer[i]);
}
The only way is to create a byte array of the same size as the short array and copy the short array elements