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
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.
I have an char array containing hex value. It contains 6 bytes. I have calculated the crc of these 6 bytes and the function returns int value.
This is the code.
char buffer[] = {0x01,0x05,0x00,0x06,0x00,0x00};
byte[] bufferbyte = new String(buffer).getBytes();
for (byte bb : bufferbyte){
System.out.format("0X%x ", bb);
}
int crcresult;
crcresult = CRC16(buffer,6); //crc calculation
byte[] crc_bytes = ByteBuffer.allocate(4).putInt(crcresult).array();
for (byte b : crc_bytes){
System.out.format("0X%x ", b);
}
My question are
I have used bytebuffer to convert crc obtained as int into byte. But the calculated crc are stored in 4 byte instead of 2 byte. I have calculated CRC 16 but the resulting crc is 32 bit . I think it is because i have returned "int" in the crc calculation and it is written that in java an int is 32 bits.
So How to extract only two bytes from the byte buffer (crc_bytes) or the calculated int crc (crcresult).
I have put the bytes of the "char buffer[]" and two bytes of calculated crc in single byte array. How can we append
char buffer[] and crcresult
in one byte array.
The output of above code is
0X1 0X5 0X0 0X6 0X0 0X0 0X0 0X0 0X2d 0Xcb
Where first 6 bytes are bytes converted from char array and last 4 bytes are crc.
The two bytes of the crc in big endian order can be fetched with
byte[] crc_result = new byte[2];
crc_bytes[0] = (byte)(crcresult >> 8); // this are the high order 8 bits
crc_bytes[1] = (byte)crcresult; // this are the low order 8 bits
If you need it in little endian order just adapt the assignments accordingly.
It is not clear to me why you use a char array to represent bytes.
Yes, crcresult is 32 bits because it is of type int. If you want a 16bit data type, use short instead.
But, using int type does not do any harm. Although it is 32 bit, only last 16 bits will contain CRC16 value. You can extract those two bytes with following bitwise operations.
byte byte1 = (byte)((crcresult >> 8) & 0xFF); // first 8 bits of last 16 bits
byte byte0 = (byte)(crcresult & 0xFF); // last 8 bits
To merge the results.
byte[] merged = new byte[bufferbyte.length + 2];
System.arrayCopy(bufferbyte, 0, merged, 0, bufferbyte.length); // copy original data buffer
merged[bufferbyte.length ] = byte1; // append crc16 byte 1
merged[bufferbyte.length + 1] = byte0; // append crc16 byte 2
Refer System.arrayCopy for more details.
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.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Convert a string representation of a hex dump to a byte array using Java?
For example, I have a string "DEADBEEF". How can I convert it to byte[] bytes = { 0xDE, 0xAD, 0xBE, 0xEF } ?
Loop through each pair of two characters and convert each pair individually:
byte[] bytes = new byte[str.length()/2];
for( int i = 0; i < str.length(); i+=2 )
bytes[i/2] = ((byte)Character.digit(str.charAt(i),16))<<4)+(byte)Character.digit(str.charAt(i),16);
I haven't tested this code out (I don't have a compiler with me atm) but I hope I got the idea through. The subtraction/addition simply converts 'A' into the number 10, 'B' into 11, etc. The bitshifting <<4 moves the first hex digit to the correct place.
EDIT: After rethinking it a bit, I'm not sure if you're asking the correct question. Do you want to convert "DE" into {0xDE}, or perhaps into {0x44,0x45} ? The latter is more useful, the former is more like a homework problem type question.
getBytes() would get you the bytes of the characters in the platform encoding. However it sounds like you want to convert a String containing a Hex representation of bytes into the actual represented byte array.
In which case I would point you toward this existing question: Convert a string representation of a hex dump to a byte array using Java? (note: I personally prefer the 2nd answer to use commons-codec but more out of philosophical reasons)
You can parse the string to a long and then extract the bytes:
String s = "DEADBEEF";
long n = Long.decode( "0x" + s ); //note the use of auto(un)boxing here, for Java 1.4 or below, use Long.decode( "0x" + s ).longValue();
byte[] b = new byte[4];
b[0] = (byte)(n >> 24);
b[1] = (byte)(n >> 16);
b[2] = (byte)(n >> 8);
b[3] = (byte)n;
tskuzzy's answer might be right (didn't test) but if you can, I'd recommend using Commons Codec from Apache. It has a Hex class that does what you need.
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 :)