I have a String array.
I want to convert it to byte array.
I use the Java program.
For example:
String str[] = {"aa", "55"};
convert to:
byte new[] = {(byte)0xaa, (byte)0x55};
What can I do?
String str = "Your string";
byte[] array = str.getBytes();
Looking at the sample I guess you mean that a string array is actually an array of HEX representation of bytes, don't you?
If yes, then for each string item I would do the following:
check that a string consists only of 2 characters
these chars are in '0'..'9' or 'a'..'f' interval (take their case into account
as well)
convert each character to a corresponding number, subtracting code value of '0' or 'a'
build a byte value, where first char is higher bits and second char is lower ones. E.g.
int byteVal = (firstCharNumber << 4) | secondCharNumber;
Convert string to Byte-Array:
byte[] theByteArray = stringToConvert.getBytes();
Convert String to Byte:
String str = "aa";
byte b = Byte.valueOf(str);
You can try something similar to this :
String s = "65";
byte value = Byte.valueOf(s);
Use the Byte.ValueOf() method for all the elements in the String array to convert them into Byte values.
A long way to go :). I am not aware of methods to get rid of long for statements
ArrayList<Byte> bList = new ArrayList<Byte>();
for(String ss : str) {
byte[] bArr = ss.getBytes();
for(Byte b : bArr) {
bList.add(b);
}
}
//if you still need an array
byte[] bArr = new byte[bList.size()];
for(int i=0; i<bList.size(); i++) {
bArr[i] = bList.get(i);
}
Since there was no answer for hex string to single byte conversion, here is mine:
private static byte hexStringToByte(String data) {
return (byte) ((Character.digit(data.charAt(0), 16) << 4)
| Character.digit(data.charAt(1), 16));
}
Sample usage:
hexStringToByte("aa"); // 170
hexStringToByte("ff"); // 255
hexStringToByte("10"); // 16
Or you can also try the Integer.parseInt(String number, int radix) imo, is way better than others.
// first parameter is a number represented in string
// second is the radix or the base number system to be use
Integer.parseInt("de", 16); // 222
Integer.parseInt("ad", 16); // 173
Integer.parseInt("c9", 16); // 201
String source = "testString";
byte[] byteArray = source.getBytes(encoding);
You can foreach and do the same with all the strings in the array.
The simplest way (using Apache Common Codec):
byte[] bytes = Hex.decodeHex(str.toCharArray());
String str[] = {"aa", "55"};
byte b[] = new byte[str.length];
for (int i = 0; i < str.length; i++) {
b[i] = (byte) Integer.parseInt(str[i], 16);
}
Integer.parseInt(string, radix) converts a string into an integer, the radix paramter specifies the numeral system.
Use a radix of 16 if the string represents a hexadecimal number.
Use a radix of 2 if the string represents a binary number.
Use a radix of 10 (or omit the radix paramter) if the string represents a decimal number.
For further details check the Java docs: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int)
Here, if you are converting string into byte[].There is a utility code :
String[] str = result.replaceAll("\\[", "").replaceAll("\\]","").split(", ");
byte[] dataCopy = new byte[str.length] ;
int i=0;
for(String s:str ) {
dataCopy[i]=Byte.valueOf(s);
i++;
}
return dataCopy;
Related
//PROBLEM SOLVED
I wrote a program to convert EBCDIC string to hex.
I have a problem with some signs.
So, I read string to bytes, then change them to hex(every two signs)
Problem is that, JAVA converts Decimal ASCII 136 sign according to https://shop.alterlinks.com/ascii-table/ascii-ebcdic-us.php to Decimal ASCII 63.
Which is problematic and wrong, becouse it's the only wrong converted character.
EBCDIC 88 in UltraEdit
//edit -added code
int[] bytes = toByte(0, 8);
String bitmap = hexToBin(toHex(bytes));
//ebytes[] - ebcdic string
public int[] toByte(int from, int to){
int[] newBytes = new int[to - from + 1];
int k = 0;
for(int i = from; i <= to; i++){
newBytes[k] = ebytes[i] & 0xff;
k++;
}
return newBytes;
}
public String toHex(int[] hex){
StringBuilder sb = new StringBuilder();
for (int b : hex) {
if(Integer.toHexString(b).length() == 1){
sb.append("0" + Integer.toHexString(b));
}else{
sb.append(Integer.toHexString(b));
}
}
return sb.toString();
}
public String hexToBin(String hex){
String toReturn = new BigInteger(hex, 16).toString(2);
return String.format("%" + (hex.length() * 4) + "s", toReturn).replace(' ', '0');
}
//edit2
Changing encoding in Eclipse to ISO-8859-1 helped, but I lose some signs while reading text from a file.
//edit3
Problem solved by changing the way of reading file.
Now, I read it byte by byte and parse it to char.
Before, it was line by line.
There is no ASCII-value of 136 since ASII is only 7 bit - everything beyond 127 is some custom extended codepage (the linked table seems to use some sort of windows-codepage, e.g. Cp1252). Since it is printing a ? it seems you are using a codepage that doesn't have a character assigned to the value 136 - e.g. some flavour of ISO-8859.
Solution.
Change encoding in Eclipse to more proper (in my example ISO-8859-1).
Change the way of reading file.
Now, I read it byte by byte and parse it to char.
Before, it was line by line and this is how I lost some chars.
private static byte[]theTestText ={0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,(byte) 0x88,(byte) 0x99,(byte) 0xAA,(byte) 0xBB,(byte) 0xCC,(byte) 0xDD,(byte) 0xEE,(byte) 0xFF};
String str= new String(theTestText); // converted the byte array to string
char ch = str.charAt(8); // extracting a specific character from string
I want to obtain the hex value from the character 'ch' as defined in the original byte array i.e. 0x88. Is there any way to get that?
To get the hexa value in a string:
String str= new String(theTestText); // converted the byte array to string
char ch = str.charAt(8); // extracting a specific character from string
String hex = String.format("%04x", (int) ch); // Converting the char to a string with its hexadecimal value
This has been bugging me for the last few hours.
I have a long string and I want to convert it to a byte array.
I want to preserve leading zeroes too.
Have tried DatatypeConverter & BigInteger methods and cant seem to get the proper result.
which is a byte array (of hex byte values).
byte[] array = str.getBytes();
This also doesn't seem to work, with all these methods I seem to be getting decimal representation of the string. I need it to be hex.
This is what I'm using at the minute:
String line;
line = file.readLine();
long seq = Long.parseLong(line);
String hexx = Long.toHexString(seq);
byte[] out = hexx.getBytes();
BTW, i am using BufferdReader for input and RandomAccessFile for output.
Any help would be appreciated.
Ok, to convert from one radix to another. Jeez!
String str = ...
int fromRadix = ...
int toRadix = ...
String out = new BigInteger(str, fromRadix).toString(toRadix);
For example, to convert the decimal number "12345" to hex:
String str = "12345";
int fromRadix = 10;
int toRadix = 16;
String out = new BigInteger(str, fromRadix).toString(toRadix);
// yields "3039"
Go away! :P
Ok, I think I have solved this by using BigInteger and it's toByeArray method.
BigInteger linenum = new BigInteger(line,10);
writer.write(linenum.toByteArray());
Actually simple solution, thanks for your efforts guys.
How can I convert ASCII values to hexadecimal and binary values (not their string representation in ASCII)? For example, how can I convert the decimal value 26 to 0x1A?
So far, I've tried converting using the following steps (see below for actual code):
Converting value to bytes
Converting each byte to int
Converting each int to hex, via String.toString(intValue, radix)
Note: I did ask a related question about writing hex values to a file.
Clojure code:
(apply str
(for [byte (.getBytes value)]
(.replace (format "%2s" (Integer/toString (.intValue byte) 16)) " " "0")))))
Java code:
Byte[] bytes = "26".getBytes();
for (Byte data : bytes) {
System.out.print(String.format("%2s", Integer.toString(data.intValue(), 16)).replace(" ", "0"));
}
System.out.print("\n");
Hexadecimal, decimal, and binary integers are not different things -- there's only one underlying representation of an integer. The one thing you said you're trying to avoid -- "the ASCII string representation" -- is the only thing that's different. The variable is always the same, it's just how you print it that's different.
Now, it's not 100% clear to me what you're trying to do. But given the above, the path is clear: if you've got a String, convert it to an int by parsing (i.e., using Integer.parseInt()). Then if you want it printed in some format, it's easy to print that int as whatever you want using, for example, printf format specifiers.
If you actually want hexadecimal strings, then (format "%02X" n) is much simpler than the hoops you jump through in your first try. If you don't, then just write the integer values to a file directly without trying to convert them to a string.
Something like (.write out (read-string string-representing-a-number)) should be sufficient.
Here are your three steps rolled up into one line of clojure:
(apply str (map #(format "0x%02X " %) (.getBytes (str 42))))
convert to bytes (.getBytes (str 42))
no actual need for step 2
convert each byte to a string of characters representing it in hex
or you can make it look more like your steps with the "thread last" macro
(->> (str 42) ; start with your value
(.getBytes) ; put it in an array of bytes
(map #(format "0x%02X " %)) ; make hex string representation
(apply str)) ; optionally wrap it up in a string
static String decimalToHex(String decimal, int minLength) {
Long n = Long.parseLong(decimal, 10);
// Long.toHexString formats assuming n is unsigned.
String hex = Long.toHexString(Math.abs(n), 16);
StringBuilder sb = new StringBuilder(minLength);
if (n < 0) { sb.append('-'); }
int padding = minLength - hex.length - sb.length();
while (--padding >= 0) { sb.append('0'); }
return sb.append(hex).toString();
}
//get Unicode for char
char theChar = 'a';
//use this to go from i`enter code here`nt to Unicode or HEX or ASCII
int theValue = 26;
String hex = Integer.toHexString(theValue);
while (hex.length() < 4) {
hex = "0" + hex;
}
String unicode = "\\u" + (hex);
System.out.println(hex);
I am having a hard time trying to convert a String containing the hexadecimal representation of some bytes to its corresponding byte array.
I am getting 32bytes using the following code:
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
Any idea how to get from the String to the array? In other words, how to do the reverse of the code above.
Thanks.
I'd try commons-codec byte[] originalBytes = Hex.decodeHex(string.toCharArray()). In fact I would use it also for the encoding part.
You can use the Integer.parseInt(String s, int radix) method to convert the hexadecimal representation back to an integer, which you can then cast into a byte. Use that to process the string two characters at a time.
Use the
String.getBytes();
method