Hex-encoded String to Byte Array - java

String str = "9B7D2C34A366BF890C730641E6CECF6F";
I want to convert str into byte array, but str.getBytes() returns 32 bytes instead of 16.

I think what the questioner is after is converting the string representation of a hexadecimal value to a byte array representing that hexadecimal value.
The apache commons-codec has a class for that, Hex.
String s = "9B7D2C34A366BF890C730641E6CECF6F";
byte[] bytes = Hex.decodeHex(s.toCharArray());

Java SE 6 or Java EE 5 provides a method to do this now so there is no need for extra libraries.
The method is DatatypeConverter.parseHexBinary
In this case it can be used as follows:
String str = "9B7D2C34A366BF890C730641E6CECF6F";
byte[] bytes = DatatypeConverter.parseHexBinary(str);
The class also provides type conversions for many other formats that are generally used in XML.

Use:
str.getBytes("UTF-16LE");

I know it's late but hope it will help someone else...
This is my code: It takes two by two hex representations contained in String and add those into byte array.
It works perfectly for me.
public byte[] stringToByteArray (String s) {
byte[] byteArray = new byte[s.length()/2];
String[] strBytes = new String[s.length()/2];
int k = 0;
for (int i = 0; i < s.length(); i=i+2) {
int j = i+2;
strBytes[k] = s.substring(i,j);
byteArray[k] = (byte)Integer.parseInt(strBytes[k], 16);
k++;
}
return byteArray;
}

That should do the trick :
byte[] bytes = toByteArray(Str.toCharArray());
public static byte[] toByteArray(char[] array) {
return toByteArray(array, Charset.defaultCharset());
}
public static byte[] toByteArray(char[] array, Charset charset) {
CharBuffer cbuf = CharBuffer.wrap(array);
ByteBuffer bbuf = charset.encode(cbuf);
return bbuf.array();
}

try this:
String str = "9B7D2C34A366BF890C730641E6CECF6F";
String[] temp = str.split(",");
bytesArray = new byte[temp.length];
int index = 0;
for (String item: temp) {
bytesArray[index] = Byte.parseByte(item);
index++;
}

I assume what you need is to convert a hex string into a byte array that equals that means the same thing as that hex string?
Adding this method should do it for you, without any extra library importing:
public static byte[] hexToByteArray(String s) {
String[] strBytes = s.split("(?<=\\G.{2})");
byte[] bytes = new byte[strBytes.length];
for(int i = 0; i < strBytes.length; i++)
bytes[i] = (byte)Integer.parseInt(strBytes[i], 16);
return bytes;
}

Related

How can i revert back hexa value of certain language word to UTF-8

I have converted regional language word to hex value and saved to DB. But How can i decode that hexa value back to regional language word.
Here is my Kannada/Telugu word to Hex value conversion
public String toHex(String b){
String s="";
for (int i=0; i<b.length(); ++i) s+=String.format("%04X",b.charAt(i)&0xffff);
System.out.println("Converted value:::"+s); //0C1C0C3E0C350C3E
return s;
}
Word i have saved is జావా
Hex value saved in database is 0C1C0C3E0C350C3E
Decoded output am getting is : >5>
Is there any way to decode the hex value back to జావా
Code used to decode is
byte[] bytes = DatatypeConverter.parseHexBinary(itemName);
String s= new String(bytes, "UTF-8");
System.out.println("Utf..."+s);
Please help...
public String fromHex(String b) {
char[] cs = new char[b.length() / 4];
for (int i = 0; i < cs.length; ++i) {
int c = Integer.parseInt(b.substring(4 * i, 4 * i + 4), 16) & 0xFFFF;
cs[i] = (char) c;
}
return new String(cs);
}
This assumes that the conversion did not meddle with negative hex values.
Or exploiting that char is UTF-16BE:
byte[] bytes = DatatypeConverter.parseHexBinary(itemName);
return new String(bytes, StandardCharsets.UTF_16);
char[] data = hexData.toCharArray();
byte[] bytes = new byte[data.length/2];
for (int i = 0; i < data.length; i += 2) {
String val = new String(data, i, 2);
bytes[i/2] = Integer.valueOf(val, 16).byteValue();
}
String text = new String(bytes, "UTF8");
You might add sanity checks, e.g. that the length of the input-array is even, etc.

String toByte and reverse, not bijective if bytes are modified

Following Code changes every byte of a string and creates a new string.
public static String convert(String s) {
byte[] bytes = s.getBytes();
byte[] convert = new byte[bytes.length];
for (int i = 0; i < bytes.length; i++) {
convert[i] = (byte) ~bytes[i];
}
return new String(convert);
}
Question: Why is convert() not bijective?
convert(convert("Test String")).equals("Test String") === false
when you use the constructor String(byte[]), it doesn't necesarily takes one letter per byte, it takes the default charset; if it is, say, UTF-8, then the constructor will try to decode some chars from two or three bytes rather than just one.
As you are using bit-complement to transform byte by byte, the result could be different when you apply the default charset.
If you are using only ASCII chars, you could try this version of your function:
// ONLY if you use ASCII as Charset
public static String convert(String s) {
Charset ASCII = Charset.forName("ASCII");
byte[] bytes = s.getBytes(ASCII);
byte[] convert = new byte[bytes.length];
for (int i = 0; i < bytes.length; i++) {
convert[i] = (byte) (~bytes[i] & 0x7F);
}
return new String(convert, ASCII);
}
Because information is lost when you converted the manipulated byte to String and vice versa
In this line below
for (int i = 0; i < bytes.length; i++) {
convert[i] = (byte) ~bytes[i];
}
return new String(convert);
If you go inside the implementation of String to byte conversion and viceversa you will find that CharSet and encoding are involved.
Read about them and you will get detailed explanation of this behavior.

How to convert a String array to a Byte array? (java)

I have a one dimensional String array that I want to convert into a one dimensional byte array. How do I do this? Does this require ByteBuffer? How can I do this? (The strings can be any length, just want to know how to go about doing such an act. And after you convert it into a byte array how could I convert it back into a String array?
-Dan
Array to Array you should convert manually with parsing into both sides, but if you have just a String you can String.getBytes() and new String(byte[] data);
like this
public static void main(String[] args) {
String[] strings = new String[]{"first", "second"};
System.out.println(Arrays.toString(strings));
byte[][] byteStrings = convertToBytes(strings);
strings = convertToStrings(byteStrings);
System.out.println(Arrays.toString(strings));
}
private static String[] convertToStrings(byte[][] byteStrings) {
String[] data = new String[byteStrings.length];
for (int i = 0; i < byteStrings.length; i++) {
data[i] = new String(byteStrings[i], Charset.defaultCharset());
}
return data;
}
private static byte[][] convertToBytes(String[] strings) {
byte[][] data = new byte[strings.length][];
for (int i = 0; i < strings.length; i++) {
String string = strings[i];
data[i] = string.getBytes(Charset.defaultCharset()); // you can chose charset
}
return data;
}
for one byte[] from string[] you have to:
to byteArray concat byte arrays from each string using some delimeter
from bytearray split by te same delimiter and create String as I
described above.
You don't say what you want to do with the bytes (aside from convert them back to a String[] afterward), but assuming you can just treat them as an opaque bag of data (so you can save them to a file or send them over the network or whatnot, but you don't need to examine or modify them in any way), I think your best bet is to use serialization. To serialize your string-array, you would write something like:
final String[] stringArray = { "foo", "bar", "baz" };
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final ObjectOutputStream objectOutputStream =
new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(stringArray);
objectOutputStream.flush();
objectOutputStream.close();
final byte[] byteArray = byteArrayOutputStream.toByteArray();
and to recover it afterward, you'd write the reverse:
final ByteArrayInputStream byteArrayInputStream =
new ByteArrayInputStream(byteArray);
final ObjectInputStream objectInputStream =
new ObjectInputStream(byteArrayInputStream);
final String[] stringArray2 = (String[]) objectInputStream.readObject();
objectInputStream.close();
You can check this
package javaapplication2;
import java.util.Arrays;
/**
*
* #author Ali
*/
public class JavaApplication2 {
public static byte[] to_byte(String[] strs) {
byte[] bytes=new byte[strs.length];
for (int i=0; i<strs.length; i++) {
bytes[i]=Byte.parseByte(strs[i]);
}
return bytes;
}
public static void main(String[] args) {
String[] input = {"1","2","3"}; //original data
byte[] byteArray = to_byte(input);//data to byte array
String[] recovered=Arrays.toString( byteArray).split(",");// recovered data
}
}
First declare the string like I declared here str="Suresh"
Second use getBytes() to convert it in bytes
getBytes returns the array of byte.
String str="Suresh";
byte[] s=str.getBytes();
String.getBytes()? is what you're looking for.
I would treat this as a serialization problem and just implemented it as follows(complete and working Java code):
import java.nio.ByteBuffer;
import java.util.ArrayList;
public class Serialization {
public static byte[] serialize(String[] strs) {
ArrayList<Byte> byteList = new ArrayList<Byte>();
for (String str: strs) {
int len = str.getBytes().length;
ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(len);
byte[] lenArray = bb.array();
for (byte b: lenArray) {
byteList.add(b);
}
byte[] strArray = str.getBytes();
for (byte b: strArray) {
byteList.add(b);
}
}
byte[] result = new byte[byteList.size()];
for (int i=0; i<byteList.size(); i++) {
result[i] = byteList.get(i);
}
return result;
}
public static String[] unserialize(byte[] bytes) {
ArrayList<String> strList = new ArrayList<String>();
for (int i=0; i< bytes.length;) {
byte[] lenArray = new byte[4];
for (int j=i; j<i+4; j++) {
lenArray[j-i] = bytes[j];
}
ByteBuffer wrapped = ByteBuffer.wrap(lenArray);
int len = wrapped.getInt();
byte[] strArray = new byte[len];
for (int k=i+4; k<i+4+len; k++) {
strArray[k-i-4] = bytes[k];
}
strList.add(new String(strArray));
i += 4+len;
}
return strList.toArray(new String[strList.size()]);
}
public static void main(String[] args) {
String[] input = {"This is","a serialization problem;","string concatenation will do as well","in some cases."};
byte[] byteArray = serialize(input);
String[] output = unserialize(byteArray);
for (String str: output) {
System.out.println(str);
}
}
}
The idea is that in the resulting byte array we store the length of the first string(which is always 4 bytes if we use the type int), followed by the bytes of the first string(whose length can be read later from the preceding 4 bytes), then followed by the length of the second string and the bytes of the second string, and so on. This way, the string array can be recovered easily from the resulting byte array, as demonstrated by the code above. And this serialization approach can handle any situation.
And the code can be much simpler if we make an assumption to the input string array:
public class Concatenation {
public static byte[] concatenate(String[] strs) {
StringBuilder sb = new StringBuilder();
for (int i=0; i<strs.length; i++) {
sb.append(strs[i]);
if (i != strs.length-1) {
sb.append("*.*"); //concatenate by this splitter
}
}
return sb.toString().getBytes();
}
public static String[] split(byte[] bytes) {
String entire = new String(bytes);
return entire.split("\\*\\.\\*");
}
public static void main(String[] args) {
String[] input = {"This is","a serialization problem;","string concatenation will do as well","in some cases."};
byte[] byteArray = concatenate(input);
String[] output = split(byteArray);
for (String str: output) {
System.out.println(str);
}
}
}
The assumption is that *.* does not exist in any string from the input array. In other words, if you know in advance some special sequence of symbols won't appear in any string of the input array, you may use that sequence as the splitter.
You can iterate for each string and keep appending to the final byte array.
String example = "This is an example";
//Convert String to byte[] using .getBytes() function
byte[] bytes = example.getBytes();
//Convert byte[] to String using new String(byte[])
String s = new String(bytes);

String(byte array) to byte array

i need to convert from string to same byte array:
String data = request.getParameter("data");
byte[] dataByte = new byte[]{};
data = -60,-33,-10,-119,126,114,-61,-31,55,-102,-35,-72,114,77,115,72,79,-117,102,64,98,-20,-75,27,58,-59,86,-97,106,19,-112,-79,100,105,115,107,100,105,114,101,99,116,111,114,95,115,97,102,101,46,99,111,110,102,105,103,49,52,53,53,83,112,97,99,101,115,83,116,111,114,101,114,117,99,111,110,116,101,110,116,85,114,108,61,115,116,111,114,101,58,47,47,50,48,49,50,47,49,48,47,49,47,57,47,53,50,47,57,100,48,48,48,48,55,97,45,54,50,48,48,45,52,54,52,102,45,97,48,48,97,45,50,52,97,100,52,98,100,55,50,53,53,48,46,98,105,110,124,109,105,109,101,116,121,112,101,61,97,112,112,108,105,99,97,116,105,111,110,47,111,99,116,101,116,45,115,116,114,101,97,109,124,115,105,122,101,61,52,53,57,53,49,124,101,110,99,111,100,105,110,103,61,85,84,70,45,56,124,108,111,99,97,108,101,61,114,117,95,124,105,100,61,52,49,48,56,101,57,100,100,50,100,56,45,56,102,54,97,45,52,54,55,54,45,56,53,99,57,45,50,52,54,102,55,57,57,55,101,102,48,99,77,111,110,32,79,99,116,32,48,49,32,48,57,58,53,50,58,49,53,32,78,79,86,83,84,32,50,48,49,50,119,111,114,107,115,112,97,99,101,97,100,109,105,110,97,100,109,105,110
String[] dataArray = data.split(",")
You can then iterate over that dataArray and then create byte[] out of it.
String dataArray[] = data.split(",");
byte[] bytes = new byte[dataArray.length];
int count = 0;
for(String str : dataArray)
{
bytes[count++] = Byte.parseByte(str);
}
If you know character encoding then you can use #String.getBytes
String.getBytes(String charsetName) will give you a byte-array. You will have to be careful re. specifying your character encoding.
Use StringTokenizer or String.split() method and parse each substring to byte. Take care with encoding.
Use String.split() and iterate over the resulting array:
String[] array = data.split(",");
byte[] dataByte = new byte[ array.length ];
for ( int i=0 ; i<array.length ; i++ ) { dataByte[ i ] = Byte.parseByte( array[ i ] ); }
Cheers,
You can use String#getBytes() method for this purpose: -
String data = request.getParameter("data");
byte[] dataByte = data.getBytes()
It uses the default character encoding.. You can specify your own..
See String#getBytes(Charset)
Or you can use Byte#parseByte(String) method in each value of the string array after splitting it: -
String data = request.getParameter("data");
String arr[] = data.split(",");
byte[] newarr = new byte[arr.length];
int count = 0;
for (String val: arr) {
newarr[count++] = Byte.parseByte(val);
System.out.println(Byte.parseByte(val) + ", ");
}

How to combine two byte arrays [duplicate]

This question already has answers here:
Easy way to concatenate two byte arrays
(13 answers)
Closed 4 years ago.
I have two byte arrays and I am wondering how I would go about adding one to the other or combining them to form a new byte array.
You're just trying to concatenate the two byte arrays?
byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];
for (int i = 0; i < combined.length; ++i)
{
combined[i] = i < one.length ? one[i] : two[i - one.length];
}
Or you could use System.arraycopy:
byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];
System.arraycopy(one,0,combined,0 ,one.length);
System.arraycopy(two,0,combined,one.length,two.length);
Or you could just use a List to do the work:
byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
List<Byte> list = new ArrayList<Byte>(Arrays.<Byte>asList(one));
list.addAll(Arrays.<Byte>asList(two));
byte[] combined = list.toArray(new byte[list.size()]);
Or you could simply use ByteBuffer with the advantage of adding many arrays.
byte[] allByteArray = new byte[one.length + two.length + three.length];
ByteBuffer buff = ByteBuffer.wrap(allByteArray);
buff.put(one);
buff.put(two);
buff.put(three);
byte[] combined = buff.array();
You can do this by using Apace common lang package (org.apache.commons.lang.ArrayUtils class ). You need to do the following
byte[] concatBytes = ArrayUtils.addAll(one,two);
I think it is best approach,
public static byte[] addAll(final byte[] array1, byte[] array2) {
byte[] joinedArray = Arrays.copyOf(array1, array1.length + array2.length);
System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
return joinedArray;
}
The simplest method (inline, assuming a and b are two given arrays):
byte[] c = (new String(a, cch) + new String(b, cch)).getBytes(cch);
This, of course, works with more than two summands and uses a concatenation charset, defined somewhere in your code:
static final java.nio.charset.Charset cch = java.nio.charset.StandardCharsets.ISO_8859_1;
Or, in more simple form, without this charset:
byte[] c = (new String(a, "l1") + new String(b, "l1")).getBytes("l1");
But you need to suppress UnsupportedEncodingException which is unlikely to be thrown.
The fastest method:
public static byte[] concat(byte[] a, byte[] b) {
int lenA = a.length;
int lenB = b.length;
byte[] c = Arrays.copyOf(a, lenA + lenB);
System.arraycopy(b, 0, c, lenA, lenB);
return c;
}
String temp = passwordSalt;
byte[] byteSalt = temp.getBytes();
int start = 32;
for (int i = 0; i < byteData.length; i ++)
{
byteData[start + i] = byteSalt[i];
}
The problem with your code here is that the variable i that is being used to index the arrays is going past both the byteSalt array and the byteData array. So, Make sure that byteData is dimensioned to be at least the maximum length of the passwordSalt string plus 32. What will correct it is replacing the following line:
for (int i = 0; i < byteData.length; i ++)
with:
for (int i = 0; i < byteSalt.length; i ++)
Assuming your byteData array is biger than 32 + byteSalt.length()...you're going to it's length, not byteSalt.length. You're trying to copy from beyond the array end.
I've used this code which works quite well just do appendData and either pass a single byte with an array, or two arrays to combine them :
protected byte[] appendData(byte firstObject,byte[] secondObject){
byte[] byteArray= {firstObject};
return appendData(byteArray,secondObject);
}
protected byte[] appendData(byte[] firstObject,byte secondByte){
byte[] byteArray= {secondByte};
return appendData(firstObject,byteArray);
}
protected byte[] appendData(byte[] firstObject,byte[] secondObject){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
try {
if (firstObject!=null && firstObject.length!=0)
outputStream.write(firstObject);
if (secondObject!=null && secondObject.length!=0)
outputStream.write(secondObject);
} catch (IOException e) {
e.printStackTrace();
}
return outputStream.toByteArray();
}

Categories

Resources