Gajen Dissanayake
Gajen Dissanayake

Reputation: 103

How to get characters to a string in Java?

I have a text file which contains the "Captured Network Packets' Headers" as hexadecimal values like this...

FC-C8-97-62-88-5F-74-DE-2B-C8-C7-E5-08-00-45-00-00-28-4E-C4-40-00-80-06-BD-65-C0-A8-01-03-AD-C2-7F-38-C9-96-01-BB-F8-01-7F-5F-B6-8A-15-22-50-10-40-42-72-8C-00-00.

I need to convert them to decimal values... I did little as here..

InputStream input = new FileInputStream("data.txt");
OutputStream output = new FileOutputStream ("converteddata.txt");
int data = input.read();
while (data != -1) 
{
  char ch = (char) data;
  output.write(ch);
  data=input.read(); 
} 
input.close(); 
output.close();

Now, my problem is... how to get each hexadecimal string which would have '2' characters..? (such as "AD" or 5F etc. in order to convert them in to decimal values).

I know that C++ has a function "fgetc()" No..? I need similar solution. Anybody can suggest a good way..? (Sorry, I'm a beginner for Java but know c++ much better) Thanks in advance.

Upvotes: 1

Views: 183

Answers (3)

Lavekush
Lavekush

Reputation: 6166

Try this:

String strHex = "FC-C8-97-62-88-5F-74-DE-2B-C8-C7-E5-08-00-45-00-00-28-4E-C4-40-00-80-06-BD-65-C0-A8-01-03-AD-C2-7F-38-C9-96-01-BB-F8-01-7F-5F-B6-8A-15-22-50-10-40-42-72-8C-00-00";

String[] hexParts = strHex.split("-");


for (String myStr : hexParts) {

  // System.out.println(toHex(myStr));
   System.out.println(toDecimal(myStr));
}


// getting For Decimal values from Hex string
public int toDecimal(String str){
    return Integer.parseInt(str.trim(), 16 );
}

// getting For Hex values
public String toHex(String arg) {
    return String.format("%x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
}

Upvotes: 1

Hirak
Hirak

Reputation: 3649

Here is a sample code. Please optimize for real time uses.

public static void main(String[] args) throws IOException {
        OutputStream output = new FileOutputStream ("converteddata.txt");
        BufferedReader br = new BufferedReader(new FileReader(new File("data.txt")));
        String r = null;
        while((r=br.readLine())!=null) {
            String [] str = r.split("-");
            for (String string : str) {
                Long l = Long.parseLong(string.trim(), 16);
                output.write(String.valueOf(l).getBytes());
                output.write("\n".getBytes());
            }

        }
        br.close(); 
        output.close();

    }

Upvotes: 0

manan
manan

Reputation: 1403

Try Long.parseLong("<hex string>", 16); to convert a hexadecimal string to a long value.

Upvotes: 1

Related Questions