Converting a byte[] to a String in Java - java

Say we have a byte[] array:
byte[] data = {10,10,1,1,9,8}
and I want to convert these values in to a hexadecimal string:
String arrayToHex = "AA1198"
How can I do this? Using Java language in IntelliJ. Keep in mind this is my first semester of coding, so I'm already feeling lost.
First I start with this method:
public static String toHexString(byte[] data)
In the problem I'm trying to solve, we get a string from a user input, which is then converted to a byte[] array, and from there must be converted back into a string in hexadecimal format. But for simplification purposes I am just trying to input my own array.
So, here I have my array:
byte[] data = {10,10,1,1,9,8}
I know how to just print the byte array by just saying:
for (int i = 0; i < data.length; i++)
{
System.out.print(data[i]);
}
which will have an output of:
10101198
but obviously this is not what I'm looking for, as I have to convert the 10s to As, and I need a String type, not just an output. I'm sorry I'm so vague, but I'm truly lost and ready to give up!

This is not what you would normally do and would only work for byte values from 0 to 15.
byte[] data = {10,10,1,1,9,8};
StringBuilder sb = new StringBuilder();
for (byte b : data)
sb.append(Integer.toHexString(b));
String arrayAsHex = sb.toString();
What you would normally expect is "0A0A01010908" so that any byte value is possible.
String arrayAsHex = DatatypeConverter.printHexBinary(data);

Related

Save a hex String to File.hex in java

I have a String which contains hex values. Now i want to write this exact string to a file with the ending .hex . How can i realize this in java?
I already tried to convert the Hex Values into ASCII and then write this string into a file.
But all Hex Values which are higher then 127(dec) can't be processed correctly.
86(hex) is transformed to ?(char), which is 3F(hex) and not 86(hex).
You can try to take each char of your string, convert it to integer and then write values in bytes in a file. To do the opposite process, you just have to read the file into a byte array and convert each byte into a char to retrieve your string. Then I'm sure you can find some algorithm to cast your string into Hex string.
For me the Answer was this:
Under Projectproperties i needed to set the Text-file-Encoding to ISO-8859-1.
Then my old procedure worked very well.
public static String hexToASCII(String hex){
if(hex.length()%2 != 0){
System.err.println("requires EVEN number of chars");
return null;
}
StringBuilder sb = new StringBuilder();
for( int i=0; i < hex.length()-1; i+=2 ){
String output = hex.substring(i, (i + 2));
int decimal = Integer.parseInt(output, 16);
sb.append((char)decimal);
}
return sb.toString();
}

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

Taking a string representation of a large integer and converting it to a byte array in Java

Basically, my problem is two-fold, and refers pretty specifically to the Bitcoin RPC. I am writing a miner in Java for Litecoin (a spinoff of BTC) and need to take a string that looks like:
000000000000000000000000000000000000000000000000000000ffff0f0000
Convert it to look like
00000fffff000000000000000000000000000000000000000000000000000000
(Which I believe is switching from little endian to big endian)
I then need to turn that string into a byte array --
I've looked at the Hex class from org.apache, String.toByte(), and a piece of code that looks like:
public static byte[] toByta(char[] data) {
if (data == null) return null;
// ----------
byte[] byts = new byte[data.length * 2];
for (int i = 0; i < data.length; i++)
System.arraycopy(toByta(data[i]), 0, byts, i * 2, 2);
return byts;
}
So essentially: What is the best way, in Java to change endianness? And what is the best way to take a string representation of a number and convert it to a byte array to be hashed?
EDIT: I had the wrong result after changing the endian.
Integer and BigInteger both have toString methods taking a radix, so
you can get the hex String.
You can make a StringBuffer from that
String and call reverse().
You then convert back to a String using
toString(), then get the bytes via getBytes();
Don't know if this is "best" but it requires little work on your part.
If you need better speed, call getBytes() on the original wrong direction hex string (from step 1) and reverse it in place using a for loop. e.g.
for (int i=0; i<bytes.length/2; i++) {
byte temp = bytes[i];
bytes[i] = bytes[bytes.length - i];
bytes[bytes.length - i] = temp;
}

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.

How should I terminate a char array before converting into a string in Java

I am reading a char array from a file in and then converting it too a string using the String constructor.
read = fromSystem.read(b);
String s = new String(b);
This code has been in the program for ages and works fine, although until now it has been reading the full size of the array, 255 chars, each time. Now I am reusing the class for another purpose and the size of what it reads varies. I am having the problem that if it reads, say 20 chars, then 15, the last 5 of the previous read are still in the byte array. To overcome this I added a null char at the end of what had been read.
read = fromSystem.read(b);
if (read < bufferLength) {
b[read] = '\0';
}
String s = new String(b);
If I then did
System.out.println(b);
It works, the end of the buffer doens't show. However, if I pass that string into a message dialog then it still shows. Is there some other way that I should terminate the string?
Use:
String s = new String(b, 0, read)
instead.
You need to use the String constructor that allows you to specify the range of bytes that are valid in the byte array.
String(byte[] bytes, int offset, int length);
Using it like this:
read = fromSystem.read(b);
String s = new String(b, 0, read);

Categories