How to append a long to a byte array in Java - 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[];

Related

How to send all byte into single array and later xor between the bytes?

I have socket application and I can read byte by byte and I need push all the byte into one single array.
I read like below.So I will have 12+bodylen bytes.
int messageID = r.readUnsignedShort();
int bodyLen = r.readUnsignedShort();
byte[] phoneNum = new byte[6];
r.readFully(phoneNum);
int serialNum = r.readUnsignedShort();
byte[] messageBody = new byte[bodyLen];
r.readFully(messageBody);
byte checkCode = r.readByte();
My challenge is how to push all the byte into one fullMessage and there after I need to xor between each of this bytes and get the results as byte too.
byte[] fullMessage = new byte[12+bodyLen];
If you dont need to have everything in separate and you need all in single array, after reading bodyLen you can do something like this:
int messageID = r.readUnsignedShort();
int bodyLen = r.readUnsignedShort();
byte[] fullMessage=new byte[12+bodyLen];
r.readFully(fullMessage,0,fullMessage.length);
Here fullMessage will contain all the data you are reading step by step in your code in single array.
But if you need all the parts to be read separately: read below
To concatenate arrays and other elements into array use ByteBuffer#put(byte[]).
After work is done, get the array from buffer using .array() method of ByteBuffer
byte[] fullMessage=byteBuffer.array();
Later on, iterate over array and do required work
for(int i=0,s=fullMessage.lengthl;i<s;i++){
// do your XOR operations -> xor operator is ^
}

convert int or long to byte hex array

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.

Convert int to byte array

I need a way to do this
String username = "Snake";
int usernameLength = username.length(); // 5
converting it to
0x05
Should I use a for loop to get each number and add a zero if the result is less than two numbers?
Try the ByteBuffer class...
byte[] byteArray = ByteBuffer.allocate(1).putInt(username.length()).array();

How to convert from ByteBuffer to Integer and String?

I converted an int to a byte array using ByteBuffer's putInt() method. How do I do the opposite? So convert those bytes to an int?
Furthermore, I converted a string to an array of bytes using the String's getBytes() method. How do I convert it the other way round? The bytesArray.getString() does not return a readable string. I get things like BF#DDAD
You can use the ByteBuffer.getInt method, specifying the offset at which the integer occurs, to convert a series of bytes into an integer. Alternatively, if you happen to know the byte ordering, you can use bitwise operators to explicitly reconstruct the 32-bit integer from its 8-bit octets.
To convert an array of bytes into a String, you can use the String(byte[]) constructor to construct a new String out of the byte array. For example:
byte[] bytes = /* ... get array of bytes ... */
String fromBytes = new String(bytes);

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