convert int or long to byte hex array - java

what is the easiest way to convert an integer or a long value to a byte buffer?
example:
input : 325647187
output : {0x13,0x68,0xfb,0x53}
I have tried a ByteBuffer like this :
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putLong(325647187);
byte[] x=buffer.array();
for(int i=0;i<x.length;i++)
{
System.out.println(x[i]);
}
but I get exception
Exception in thread "main" java.nio.BufferOverflowException
at java.nio.Buffer.nextPutIndex(Buffer.java:527)
at java.nio.HeapByteBuffer.putLong(HeapByteBuffer.java:423)
at MainApp.main(MainApp.java:11)

You allocated a 4 bytes buffer, but when calling putLong, you attempted to put 8 bytes in it. Hence the overflow. Calling ByteBuffer.allocate(8) will prevent the exception.
Alternately, if the encoded number is an integer (as in your snippet), it's enough to allocate 4 bytes and call putInt().

you can try this for an easier way of converting:
so you have 325647187 as your input, we can then have something like this
byte[] bytes = ByteBuffer.allocate(4).putInt(325647187).array();
for (byte b : bytes)
{
System.out.format("0x%x ", b);
}
for me this is(if not the most) an efficient way of converting to byte buffer.

Related

How to append a long to a byte array in Java

How do you append a long to a byte array in Java?
I would like to convert the long to bytes and then add it to the byte array.
byte[] combined;
long number;
byte[] bytes = {...}
combined = ???
One approach is to use NIO's ByteBuffer:
byte[] bytes = ...
long number = ...
ByteBuffer buf = ByteBuffer.allocate(bytes.length+8);
buf.put(bytes);
buf.putLong(number);
byte[] result = buf.array();
You allocate the buffer of sufficient length, then copy the array to which you wish to append a byte representation of your long value, and then call myLong to append it to the array. Calling buf.array() harvests the result from the buffer.
lets just say your byte array is of n size. Now just do this,
bytes[n+1]= number;
combined[]= bytes[];

Convert String to byte array (0x) - Java

I have a String value as "0x0601930600058000050001", need to convert to byte array
byte[] codes1 = new byte[]{(byte)0x06,(byte)0x01,(byte)0x93,(byte)0x06,(byte)0x00,(byte)0x05,(byte)0x80,(byte)0x00,(byte)0x05,(byte)0x00,(byte)0x01};
for(byte b : codes1){
System.out.println(b);
}
System.out.println("======================");
byte[] cod = "0x0601930600058000050001".getBytes();
for(byte b : cod){
System.out.println(b);
}
Both the results are different, how to make them same. 1st loop output is the actual one what i am expecting, 2nd loop is wrong output.
If you see, i am splitting each 2 bytes and type casting and using 0x to get the actual value.
Question : Is there any predefined method (Apache commons codec) which can help me to do the same task as 1st loop ? I get that String value dynamically at run time.
Please suggest.
Thanks!
Your string is a hexadecimal representation of a byte array!
With guava you can do this:
byte[] bytes = BaseEncoding.base16().decode(mystring)
I would go for:
byte[] result = myString.getBytes();
or
byte[] result = myString.getBytes(Charset.forName("UTF-8"));

Decoding bytes from InputStream

If I had a byte stream which is encoded with the following format:
0x20 Length D_1 D_2 ... D_n CS
0x20...marks the beginning of a data frame
Length...number of bytes following
D_1-D_n...data bytes (interpreted as signed ints)
CS...One Byte Checksum
Example:
0x20 0x05 0x01 0x02 0xD1 0xA1 0xAF
0x20 0x05 0x12 0x03 0x02 0x3A 0xF2
...
...
How would I decode this byte stream from an InputStream in a way which is common and efficient? My idea is to use a BufferedInputStream and the following procedure (in pseudo code):
BufferedInputStream bufIS = new BufferedInputStream(mInStream);
while (true ) {
byte startFrame = bufIS.read();
if(startFrame == 0x20) { //first byte must mark the beginning of a data frame
int length = bufIS.read();
byte dataframe[] = new bye[length];
for (int i = 0; i<length i++) { //read data bytes
dateframe[i] = bufIS.read();
}
if(verifyChecksum(bufIS.read()) postEvent(dataframe);
}
}
Is this an appropriate way for receiving the data frames from the InputStream? I cant't think of a better solution for this. Also there's an alternative read(byte[] b, int off, int len) method which reads chunks of bytes from the stream but it's not guaranteed that len number of bytes are read, so i think this is not helpful in my case.
Id use an ObjectInputStream with custom deserialization.
So you'd write a class that has a List of ints and implements readObject such that when given an inputstream it reads the constant (and discards it), then the length, then n ints, then the checksum, and optionally validates it.
This keeps all the code in one place, and allows you to just read fully formed objects from your data stream.
I'd did work on binary serialization at some stage and we did use BufferedInputStream with the read() method. Even more since we were using a network stream end the 'len' is almost always unrespected.
What we did instead was writing our own helper method the took a length and the buffer as parameters then return those byte for decoding use that we needed. We used that only when we are certain that we will get the full length of byte in our stream (well as long as it's a valid stream that we read)

How to put a string into a position in a byte array in Java?

I've pretty much reached a brick wall and could use some advice on how to proceed with a project for one of my courses. Here's code I'm trying to get to work:
for(i = 0; i < sendData.length; i++){
String hex = Integer.toHexString(C[i]);
}
System.out.println("Encrypted Message: ");
for(i = 0; i < sendData.length; i++){
System.out.print(sendData[i]);
}
As a bit of a background this is for code for RC4 encryption. I've trying to put the value of hex in a position in sendData[] which is a fixed byte array. Because hex is a string I haven't really found a way to put that value in a position in the sendData array. I know I can't use the getBytes() function as it completely gets rid of the hex values. If anyone has any idea on how to take a string value and put it into a position in a fixed byte array it'd be greatly appreciated.
You need to understand Integer is of 4 bytes not a single byte so you will need array 4 bytes rather than storing in loop with single bytes. You can convert an Integer to byte[] like below.
public static byte[] toByteArray(int value)
{
ByteBuffer bb = ByteBuffer.allocate(4);
return bb.putInt(value).array();
}
public long toInteger(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.put(bytes);
return buffer.getInt();
}

Java: Conversion of String to byte array, then to long value and vice versa

Basically, I'm looking for .NET's BitConverter.
I need to get bytes from String, then parse them to long value and store it. After that, read long value, parse to byte array and create original String. How can I achieve this in Java?
Edit: Someone did already ask similar question. I am looking more like for samples then javadoc reference ...
String has a getBytes method. You could use this to get a byte array.
To store the byte-array as longs, I suggest you wrap the byte-array in a ByteBuffer and use the asLongBuffer method.
To get the String back from an array of bytes, you could use the String(byte[] bytes) constructor.
String input = "hello long world";
byte[] bytes = input.getBytes();
LongBuffer tmpBuf = ByteBuffer.wrap(bytes).asLongBuffer();
long[] lArr = new long[tmpBuf.remaining()];
for (int i = 0; i < lArr.length; i++)
lArr[i] = tmpBuf.get();
System.out.println(input);
System.out.println(Arrays.toString(lArr));
// store longs...
// ...load longs
long[] longs = { 7522537965568945263L, 7955362964116237412L };
byte[] inputBytes = new byte[longs.length * 8];
ByteBuffer bbuf = ByteBuffer.wrap(inputBytes);
for (long l : longs)
bbuf.putLong(l);
System.out.println(new String(inputBytes));
Note that you probably want to store an extra integer telling how many bytes the long-array actually stores, since the number of bytes may not be a multiple of 8.

Categories