Convert int to byte array - java

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();

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[];

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 ^
}

String of 0's and 1's to File as bits

I am working on a Huffman java application and i'm almost done. I have one problem though. I need to save a String of something like: "101011101010" to a file. When I save it with my current code it saves it as characters which take up 1 byte every 0 or 1. I'm pretty sure it's possible to save every 0/1 as a bit.
I already tried some things with BitSet and Integer.valueOf but I can't get them to work. This is my current code:
FileOutputStream fos = new FileOutputStream("encoded.bin");
fos.write(encoded.getBytes());
fos.close();
Where 'encoded' is a String which can be like: "0101011101".
If I try to save it as integer the leading 0 will be removed.
Thanks in advance!
EDIT: Huffman is a compression method so the outputted file should be as small as possible.
I think I found my answer. I put the 1's and 0's in a BitSet using the following code:
BitSet bitSet = new BitSet(encoded.length());
int bitcounter = 0;
for(Character c : encoded.toCharArray()) {
if(c.equals('1')) {
bitSet.set(bitcounter);
}
bitcounter++;
}
After that I save it to the file using bitSet.toByteArray()
When I want to read it again I convert it back to a bitset using BitSet.valueOf(bitSet.toByteArray()). Then I loop through the bitset like this:
String binaryString = "";
for(int i = 0; i <= set.length(); i++) {
if(set.get(i)) {
binaryString += "1";
} else {
binaryString += "0";
}
}
Thanks to everyone who helped me.
Binary files are limited to storing bits in multiples of eight. You can solve this problem by chopping the string into eight-bit chunks, converting them to bytes using Byte.parseByte(eightCharString, 2) and adding them to a byte array:
Compute the length of the byte array by dividing the length of your bit string by eight
Allocate an array of bytes of the desired length
Run a loop that takes substrings from the string at positions representing multiples of eight
Parse each chunk, and put the result into the corresponding byte
Call fos.write() on the byte array
Try this.
String encoded = "0101011101";
FileOutputStream fos = new FileOutputStream("encoded.bin");
String s = encoded + "00000000".substring(encoded.length() % 8);
for (int i = 0, len = s.length(); i < len; i += 8)
fos.write((byte)Integer.parseInt(s.substring(i, i + 8), 2));
fos.close();

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