Re: Reading Binary File Values
On Oct 15, 1:07 pm, Eric Sosman <Eric.Sos...@sun.com> wrote:
garyi...@yahoo.com wrote:
Hello.
I have a file that was transferred from a mainframe environment. Due
to the way that this mainframe data is stored, the file was
transferred to a PC as binary data.
I am trying to read this file and display the proper field values but
am not sure how to approach this.
The file layout is as follows:
The file contains 3 10-bytes records. For simplicity sake, I will
concentrate on the first record.
Field 1: Length: 1 Bytes 1-1 Hex Value FF
(Dec Value 255)
Field 2: Length: 2 Bytes 2-3 Hex Value D34=
A (Dec
Value 54090)
Field 3: Length: 3 Bytes 4-6 Hex Value 04B=
2C1 (Dec
Value 307905)
Field 4: Length: 4 Bytes 7-10 Hex Value 03DF15=
AB (Dec
Value 64951723)
How would I go about convert these hex values back to there decimal
values?
I've tried using parseInt and I've also tried using convert the bytes
to a string which I could then feed to soem other processing I've
found which successfully converts teh hex string to teh decimal value.
The stumper for me is getting the bytes files successfully into the
proper format (string or integer).
Any help/guidance/clues would be much appreciated.
Use some kind of InputStream (probably FileInputStream, maybe
wrapped in a BufferedInputStream) and read the record into an array
of ten bytes:
InputStream stream = ...;
byte[] rec = new byte[10];
int len = stream.read(rec);
if (len != 10) ... something odd happened ...;
Then use ordinary arithmetic manipulations to assemble the bytes into
larger units of information, like Java ints:
int field1 = rec[0] & 0xFF;
int field2 = (rec[1] & 0xFF) << 8 | (rec[2] & 0xFF);
int field3 = (rec[3] & 0xFF) << 16 | (rec[4] & 0xFF) <<=
8
| (rec[5] & 0xFF);
int field4 = (rec[6] & 0xFF) << 24 | (rec[7] & 0xFF) <<=
16
| (rec[8] & 0xFF) << 8 | (rec[9] & 0xFF);
Those ugly "& 0xFF" operations are because Java's byte is a signed type
with values from -128 to +127 -- an unfortunate decision by Java's
inventors, IMHO, but that's the way it is.
--
Eric.Sos...@sun.com
Also,
I found the following piece of code online that does exactly what I
want, but it expects the input to be a string variable. If I could
get the individual bytes properly into a string, I could use the
following logic:
import java.io.*;
import java.lang.*;
public class HexaToChar{
public static void main(String[] args) throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader
(System.in));
System.out.println("Enter the hexa number:");
String str= bf.readLine();
int i= Integer.parseInt(str,16);
System.out.println("Decimal:="+ i);
}
}