Reading hex file in java

Hex Viewer in Java

I’m a beginner in java programming and i’m trying to create a hex viewer in java, my IDE is Netbeans. Below is the code.

import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import static java.lang.System.out; import javax.swing.JFileChooser; public class hope < public static void main(String[] args) throws IOException < JFileChooser open = new JFileChooser(); open.showOpenDialog(null); File f = open.getSelectedFile(); InputStream is = new FileInputStream(f); int bytesCounter = 0; int value = 0; StringBuilder sbHex = new StringBuilder(); StringBuilder sbResult = new StringBuilder(); while ((value = is.read()) != -1) < //convert to hex value with "X" formatter sbHex.append(String.format("%02X ", value)); //if 16 bytes are read, reset the counter, //clear the StringBuilder for formatting purpose only. if (bytesCounter == 15) < sbResult.append(sbHex).append("\n"); sbHex.setLength(0); bytesCounter = 0; >else < bytesCounter++; >> //if still got content if (bytesCounter != 0) < //add spaces more formatting purpose only for (; bytesCounter < 16; bytesCounter++) < //1 character 3 spaces sbHex.append(" "); >sbResult.append(sbHex).append("\n"); > out.print(sbResult); is.close(); > > 

The problem are: 1. It doesn’t read the files fast enough»It takes a minute to read a file of 200kb» 2. It gives «Out of Memory» error when I tried a large file e.g. 80mb What I want it to do: 1. Display all the hex code in seconds «Read and display hex of any size of file» 2. read file of any size without error code. The Question: What do I need to change or add in my code to achieve the above «What I want it to do»?

Читайте также:  Php функции типов данных

Thank you @DevilsHnd, I checked it out, but the code was created since 2009, which I think there are lots of improvement to do, and for what reason I couldn’t make it to work, remember I’m newbie. Java codes without comments makes it hard for me to understand and edit.

Why not use only out.print () , instead of sbHex.append () and sbResult.append () ? Maybe using StringBuilder is unnecessary ?

@gregn3 well I edited the code, and removed all unnecessary codes, but still nothing. Same speed and memory issue when tried to load a big file. checkout this link, the Hex editor was created in java and read a file up to 9 exabytes. (search.maven.org/…). I just want to be able to view it, I don’t want to edit the hex. So, how does the developer manage to open file of that size without memory leaking and how does it open fast?

@KingAmada I tried your original example on a 5.5 MB file. It took about 20 seconds to read and 20 seconds to print out the contents. I think that other app is not reading the entire file, only a small piece at a time. (Which is displayed on the screen I guess). You could try RandomAccessFile to read/write a file in small pieces. Use the seek() method to set the read position in the file.

Источник

Java Implementation for Retaining Hexadecimal Values from Hex Files

The first scenario involves a decimal value of 400 which has a corresponding hexadecimal value of 0x190. The methods getYHHeight() and getYHHeight() should return 1 and 90 respectively. In the second scenario, the decimal value is 124 which has a corresponding hexadecimal value of 0x7C. In this case, getYLHeight() should return 7C while getYHHeight() should return 0. It’s worth noting that the first scenario works smoothly because the hexadecimal values are integers, which is not the case in the second scenario. The challenge is to modify the code to work for both scenarios. As a solution, dividing by 256 is the right approach instead of 100. Although I attempted to save the values in a certain method, they still automatically convert to decimal values.

Читайте также:  Импортировать изображение в питон

Reading hex files keaping hex values in java

To extract a specific hex values value from a hexadecimal file at java code, I attempted using BufferedReader and storing the result in StringBuilder . However, the values were automatically transformed into decimal values when I applied the StringBuilder.toString() method. My aim is to retrieve the hex values value without any conversions and store it in a String or another format.

Utilize the code java.util.Formatter and experiment with it using the following method:

StringBuilder _stringBuilder = new StringBuilder(); for (byte _byte : byteArray)

Java store hexadecimal value Code Example, seconds to hours java; Write a program that prints the next 20 leap years. Write a program that prints a multiplication table for numbers up to 12. declaração de matriz em java; TreeMap headMap(K toKey boolean inclusive) method in java; Create matrix with user input in java; java leap years; area of isosceles triangle in …

How to convert Hexadecimal value to byte in java

I created a pair of functions that take in an integer and transform it into both a hexadecimal value and a returns byte value.

The value of Scenario 1 is 400 and its hexadecimal representation is 0x190. The expected return value of getYLHeight() is 90, while getYHHeight() should return 1.

The value of Scenario 2 is 124, represented in hexadecimal as 0x7C. When calling getYLHeight(), the expected value is 7C, while getYHHeight() should return 0.

While Scenario 1 runs smoothly due to the fact that the Hexadecimal values are integers, the same cannot be said for Scenario 2, where the conversion of the Hexadecimal value 7C to an integer is not possible.

Is there an alternative method to write the code that can function for both situations?

 System.out.println("YL -" + hw.getYLHeight(400));//Hex value - 0x190,should return 90 - WORKS System.out.println("YH -" + hw.getYHHeight(400));//Hex value - 0x190,should return 1 - WORKS //System.out.println(hw.getYLHeight(124));//Hex value - 0x7C should return 7C - DOES NOT WORK //System.out.println(hw.getYHHeight(124));//Hex value - 0x7C should return 0 - DOES NOT WORK private byte getYLHeight(int height) < int hexNewImageBytesLength = Integer.parseInt(Integer.toHexString(height)); byte yl = (byte)(hexNewImageBytesLength % 100); return yl; >private byte getYHHeight(int height) < int hexNewImageBytesLength = Integer.parseInt(Integer.toHexString(height)); byte yh = (byte)(hexNewImageBytesLength / 100); return yh; >

The correct value to divide by is 256, not 100. Dividing by 100 is incorrect.

It’s unnecessary to go through all of that trouble.

private static byte getYLHeight(int height) < return (byte) height; >private static byte getYHHeight(int height) < return (byte) (height >>> 8); > 

Utilize printf to obtain both hex and decimal values when printing byte .

System.out.printf("YL: hex=%1$02x, decimal=%1$d%n", Byte.toUnsignedInt(hw.getYLHeight(400))); System.out.printf("YH: hex=%1$02x, decimal=%1$d%n", Byte.toUnsignedInt(hw.getYHHeight(400))); 
YL: hex=90, decimal=144 YH: hex=01, decimal=1 

To obtain a String that displays the 2-digit hex representation of byte , follow this alternative approach.

private static String getYLHeight(int height) < return String.format("%02x", height & 0xFF); >private static String getYHHeight(int height) < return String.format("%02x", (height >>> 8) & 0xFF); > 
System.out.println("YL - " + hw.getYLHeight(400)); System.out.println("YH - " + hw.getYHHeight(400)); 

Java to hexadecimal Code Example, “java to hexadecimal” Code Answer’s. java decimal to hexa . java by Colorful Caiman on May 11 2021 Comment . 3. String to hexadecimal in java . java by Nutty Newt on Feb 18 2021 convert two bytes to int java; java store hexadecimal value;

Java Program to save decimal

Suppose you need to truncate the value 0.10705921712947473 to only its initial 3 decimal places. Initially, declare the values.

double val = 320.0 / 2989.0; BigDecimal big = new BigDecimal(val);

To save three decimal places, use the setScale() method and set its parameter as 3.

big = big.setScale(3, RoundingMode.HALF_DOWN);

Example

import java.math.BigDecimal; import java.math.RoundingMode; public class Demo < public static void main(String[] args) < double val = 320.0 / 2989.0; BigDecimal big = new BigDecimal(val); System.out.println(String.format("Value = %s", val)); // scale big = big.setScale(3, RoundingMode.HALF_DOWN); double val2 = big.doubleValue(); System.out.println(String.format("Scaled result = %s", val2)); >>

Output

Value = 0.10705921712947473 Scaled result = 0.107

Hexadecimal integer literal in Java, For Hexadecimal, the 0x or 0X is to be placed in the beginning of a number. Note − Digits 10 to 15 are represented by a to f (A to F) in Hexadecimal. Here are some of the examples of hexadecimal integer literal declared and initialized as int.

java print hex format

System.out.println(String.format("0x%08X", 1));

java store hexadecimal value

Java Program to Convert Hex String to Byte Array, Byte Array – A Java Byte Array is an array used to store byte data types only.The default value of each element of the byte array is 0. Given a byte array, the task is to convert the Hex String to Byte Array.. Example: Input — Hex String : «2f4a33» Output — Byte Array : 47 74 51 Input — Hex String : «3b4a11» …

Источник

Java reading hex values into an array of type int

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!

5 Answers 5

// 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] + " mt24">
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f2.5%2f" data-se-share-sheet-license-name="CC BY-SA 2.5" data-s-popover-placement="bottom-start">Share
)">edited Sep 30, 2010 at 20:29
answered Sep 30, 2010 at 20:20
1
    I like this output "cafe" and "bebe"
    – WorkaroundNewbie
    Jan 5, 2017 at 5:47
Add a comment|
1

I'm guessing you mean ascii hex? In that case there isn't a trivial way, but it's not hard.

You need to know exactly how the strings are stored in order to parse them.

IF they are like this:

1203 4058 a92e

then you need to read the file in and use spaces and linefeeds (whitespace) as separators.

Figure out how to get it into strings where each string ONLY contains the hex digits of a single number then call

Источник

Hex & Binary read / write in Java

The flexibility of this language is just outstanding. In it’s own organized way, you can read binary files and get the hex code or even the binary code. Then you can also write your data back to a binary file. Here is how…

To read in binary, you need to use the FileInputStream, or any equivalent that has a read method returning an int. Then, you can convert the read data into hex or binary with the Integer’s methods toBinaryString and toHexString. Here is a small example:

import java.io.FileInputStream; . private void printHexFile(String filename) < FileInputStream in = new FileInputStream(filename); int read; while((read = in.read()) != -1)< System.out.print(Integer.toHexString(read) + "\t"); >> private void printBinaryFile(String filename) < FileInputStream in = new FileInputStream(filename); int read; while((read = in.read()) != -1)< System.out.print(Integer.toBinaryString(read) + "\t"); >>

This way you can get the data of any file and print it in hex or binary. If you want to change some data in hex or binary mode and want to store them into a file you have to convert your hex/binary back into int and then save them with a simple write that gets as an argument an int such as the one that the FileOutputStream has. To convert your hex/binary to int you can use the parseInt method like this:

//convert the String to int which has a base two. int num1 = Integer.parseInt("01001100", 2); //convert the String to int that has a base of 16 int num2 = Integer.parseInt("FF", 16);

This way you can read data from a file in hex or binary, make any changes you want and then save them back to the file. Ofcourse, you can use bitwise operators such as & etc if it suits you. This way it is slower but it is more easily to understand.

3 Comments

I’ve created a file using a hex editor and filled it with values from 00 to ff. I then read that file in and view my results via the System.out.println, but values 80 through 9f are messed up. Nothing special about the code, just using a FileReader class with the read() method. Any help you could provide would be great. Let me know if you need the code. Doug

I should probably add the values show up as random numbers although the following all show up as 3f: 81, 8D, 8F, 90, 9D…interestingly the unicode values indicate those above are “not used”

Hey there Doug. In order to print hex values from a file, you have to read them in as int and then use the toHexString method from the Integer class (as you see in the code above). Have you done that? If you try and read them as strings or print them out directly as int you probably will get the errors you’re mentioning…

Источник

Оцените статью