I want to convert a string by single char to 5 hex bytes and a byte represent a hex number:
like
String s = "ABOL1";
to
byte[] bytes = {41, 42, 4F, 4C, 01}
I tried following code , but Byte.decode got error when string is too large, like "4F" or "4C". Is there another way to convert it?
String s = "ABOL1";
char[] array = s.toCharArray();
for (int i = 0; i < array.length; i++) {
String hex = String.format("%02X", (int) array[i]);
bytes[i] = Byte.decode(hex);
}
Is there any reason you are trying to go through string? Because you could just do this:
bytes[i] = (byte) array[i];
Or even replace all this code with:
byte[] bytes = s.getBytes(StandardCharsets.US_ASCII);
You can convert from char to hex String with String.format():
String hex = String.format("%04x", (int) array[i]);
Or threat the char as an int and use:
String hex = Integer.toHexString((int) array[i]);
Use String hex = String.format("0x%02X", (int) array[i]); to specify HexDigits with 0x before the string.
A better solution is convert int into byte directly:
bytes[i] = (byte)array[i];
The Byte.decode() javadoc specifies that hex numbers should be on the form "0x4C". So, to get rid of the exception, try this:
String hex = String.format("0x%02X", (int) array[i]);
There may also be a simpler way to make the conversion, because the String class has a method that converts a string to bytes :
bytes = s.getBytes();
Or, if you want a raw conversion to a byte array:
int i, len = s.length();
byte bytes[] = new byte[len];
String retval = name;
for (i = 0; i < len; i++) {
bytes[i] = (byte) name.charAt(i);
}
Related
Below is my code to convert a string into its ascii equivalent. The string will contain only numbers - which is why I am allocating 2 byte for each character (since 1 to 9 is 49 to 58 in ascii respectively)
But I am getting a java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method) . Any idea why this is happening? Keep in mind that I will be only putting in numbers as Strings as mentioned before.
public byte[] intToAscii(String assetId) { // class main
int stringLength = assetId.length();
byte[] retBuf = new byte[stringLength];
int offset = 0;
for(int i = 0; i < stringLength ; i++){
char character = assetId.charAt(i);
byte ascii = (byte) character;
System.arraycopy(ascii, 0, retBuf, offset, 1);
offset += 1;
}
return retBuf;
}
The first and third parameter to arraycopy must be arrays, and ascii is a byte, not a byte[].
If you want to convert the string assetId to ASCII bytes, just call getBytes():
public byte[] intToAscii(String assetId) {
return assetId.getBytes(StandardCharsets.US_ASCII); // or getBytes("US-ASCII") if pre-Java 7
}
I have 0 and 1 String type combination with total 256 length.
How can I convert it to hexadecimal?
I can do it with combination for 64 or less length, but cant do the same when the length is 256
could you help me please? Any example?
Many thanks in advance.
Simplest way is to use BigInteger. It's capable to convert String of any length as long as you have enough memory:
String str = "100010110101...";
String hex = new BigInteger(str, 2).toString(16);
It's also not very difficult to implement this conversion without using the intermediate BigInteger just splitting the input string into fixed length chunks (works for arbitrary length input strings as well):
public static String binToHex(String str) {
int l = str.length();
StringBuilder result = new StringBuilder();
int cur = 0;
for (int next = l - l / 32 * 32; next <= l; next += 32) {
result.append(Long.toHexString(Long.parseLong(
str.substring(cur, next), 2)));
cur = next;
}
return result.toString();
}
I have a pcap file and I can view the hex and human-readable string equivalent of the hexdump using wireshark. However, I want to do the same but in Java. Here is a screenshot from Wireshark application.
Taking the highlighted string, this is what i've come but the output is not what I've expect. Can someone help me? Thank you very much
String hex = "a106020110020138";
byte[] bts = new byte[hex.length() / 2];
for (int i = 0; i < bts.length; i++) {
bts[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
}
String c = new String(bts, StandardCharsets.US_ASCII);
System.out.println(c);
This is the output:
Java uses UTF-16 for characters, in what byte order i forgot, meaning you need to use two bytes per character.
If you want the output to look exactly like Wireshark's, you can do by reading each group of two hex digits, and keeping that ones that correspond to printable ASCII characters:
public class Pcap {
public static void main(String[] args) {
String hex = "701c2f676c08a106020110020138";
int n = hex.length();
char[] cs = new char[n / 2];
for (int i = 0; i < n; i+=2)
cs[i/2] = (char) Integer.parseInt(hex.substring(i, i+2), 16);
for (int i = 0; i < cs.length; i++)
if (cs[i] < ' ' || cs[i] > '~') // printable ASCII
cs[i] = '.';
System.out.println(new String(cs));
}
}
which outputs
p./gl........8
However, my guess is that you're better off using a library that can parse pcaps (I mentioned one earlier, it looks like http://jpcap.sourceforge.net might also work), since just getting that hex string in the first place required opening Wireshark. You can write the code yourself to pull those values from the (binary) pcap file, but projects already exist to do that.
I want to take a binary in the text area and convert it to hex. When calculated using the calculator, result is "E0AC882AA428B6B8", but with my code result is "30".
String str = txtXOR.getText();
char[] chars = str.toCharArray();
StringBuffer hex = new StringBuffer();
int x = chars.length;
for(int i = 0; i < x; i++){
hex.append(Integer.toHexString((int)chars[i]));
txtXORToHexa.setText(Integer.toHexString((int) chars[i]));
}
Could someone point out where I have gone wrong?
You should use Integer#parseInt(String s, int radix) with base 2 to parse the binary string and then use toHexString to get the Hex String:
String binaryStr = txtXOR.getText();
int number = Integer.parseInt(binaryStr, 2);
String hexStr = Integer.toHexString(number);
txtXORToHexa.setText(hexStr);
In case you must support very large number you can use BigInteger:
String binaryStr = txtXOR.getText();
BigInteger number = new BigInteger(binaryStr, 2);
String hexStr = number.toString(16);
txtXORToHexa.setText(hexStr);
How to convert string into bits(not bytes) or array of bits in Java(i will do some operations later) and how to convert into array of ints(every 32 bits turn into the int and then put it into the array? I have never done this kind of conversion in Java.
String->array of bits->(some operations I'll handle them)->array of ints
ByteBuffer bytes = ByteBuffer.wrap(string.getBytes(charset));
// you must specify a charset
IntBuffer ints = bytes.asIntBuffer();
int numInts = ints.remaining();
int[] result = new int[numInts];
ints.get(result);
THIS IS THE ANSWER
String s = "foo";
byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
// binary.append(' ');
}
System.out.println("'" + s + "' to binary: " + binary);
You are looking for this:
string.getBytes();
Not list, it's an array but you can use it later on, even to convert it to integers.
Well, maybe you can skip the String to bits conversion and convert directly to an array of ints (if what you want is the UNICODE value of each character), using s.toCharArray() where s is a String variable.
This will convert "abc" to byte and then the code will print "abc" in respective ASCII code (ie. 97 98 99).
byte a[]=new byte[160];
String s="abc";
a=s.getBytes();
for(int i=0;i<s.length();i++)
{
System.out.print(a[i]+" ");
}
May be so (I have no compiler in my current computer and don't test if it work, but it can help you a bit):
String st="this is a string";
byte[] bytes=st.getBytes();
List<Integer> ints=new ArrayList<Integer>();
ints.addAll(bytes);
If compiler fails in
ints.addAll(bytes);
you can replace it with
for (int i=0;i<bytes.length();i++){
ints.add(bytes[i]);
}
and if you want to get exactly array:
ints.toArray();
Note that string is a sequence of chars, and in Java each char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive). In order to get char integer value do this:
String str="test";
String tmp="";
int result[]=new int[str.length()/2+str.length()%2];
int count=0;
for(char c:str.toCharArray()) {
tmp+=Integer.toBinaryString((int)c);
if(tmp.length()==14) {
result[count++]=Integer.valueOf(tmp,2);
//System.out.println(tmp+":"+result[count-1]);
tmp="";
}
}
for(int i:result) {
System.out.print(i+" ");
}