Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reading hex values into an array of type int

Tags:

java

I have a file which contains integer numbers represented in hexadecimal IS there any way to store all of these numbers into an array of integers.

I know you can say int i = 0x

but I cannot do this when reading in the values I got an error?

Thanks in advance!

like image 892
Bob Avatar asked Sep 30 '10 20:09

Bob


1 Answers

You probably want to go through Integer.parseInt(yourHexValue, 16).

Example:

// Your reader
BufferedReader sr = new BufferedReader(new StringReader("cafe\nBABE"));

// Fill your int-array
String hexString1 = sr.readLine();
String hexString2 = sr.readLine();

int[] intArray = new int[2];
intArray[0] = Integer.parseInt(hexString1, 16);
intArray[1] = Integer.parseInt(hexString2, 16);

// Print result (in dec and hex)
System.out.println(intArray[0] + " = " + Integer.toHexString(intArray[0]));
System.out.println(intArray[1] + " = " + Integer.toHexString(intArray[1]));

Output:

51966 = cafe
47806 = babe
like image 70
aioobe Avatar answered Nov 14 '22 23:11

aioobe