i have a file that contains hexadecimal values and i want to convert them to int
how do u do that exactly??

import java.util.Scanner;
import java.io.File;
import java.io.IOException;

public class CacheSimulation
 {
 public static void main(String args[])
  throws IOException
  {
   int hexAdd [] = new int [32]; //array to store the vallues
   Scanner diskScanner = new Scanner (new File ("addressfile.txt")); //file containing the hexadecimal values
   
   for (int positionNum = 0; positionNum < 32; positionNum++) 
    {
     hexAdd[positionNum] = diskScanner.nextLine(); // <--- is there a different way of reading hexadecimal values from this file,as ints wont work.???????
    }
   System.out.println("Position Number\tHexadecimal Address");
   
   for (int positionNum = 0; positionNum < 32; positionNum++)
    {
    System.out.print(positionNum);
    System.out.print("\t");
    System.out.println(hexAdd[positionNum]);
    }
   }
  }

Recommended Answers

All 4 Replies

hexAdd[positionNum] = Integer.parseInt(diskScanner.nextLine());

Is this what you're looking for?

compiling but at run time outputs

Exception in thread "main" java.lang.NumberFormatException: For input string: "0000 "
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Integer.parseInt(Integer.java:458)
    at java.lang.Integer.parseInt(Integer.java:499)
    at CacheSimulation.main(CacheSimulation.java:15)

these are the values on the file


0000
0004
000c
2200
00d0
00e0
1130
0028
113c
2204
0010
0020
0004
0040
2208
0008
00a0
0004
1104
0028
000c
0084
000c
3390
00b0
1100
0028
0064
0070
00d0
0008
3394

Ah right, as long as it has "c"s and "d"s in it, you can't make it an int directly. There might be some sort of converter code that I don't know about. I'd google "java convert hex to int"

EDIT:

String hex = "2A"; //The answer is 42  
int intValue = Integer.parseInt(hex, 16);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.