Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

working with binary or HEX data

Status
Not open for further replies.

Bong

Programmer
Dec 22, 1999
2,063
US
I'm trying to do something I know how to do in Tcl but not, apparently in Java:

I have a binary file. It consists of sequential uniform length records (lets say 256 bytes each). I want to read 1 record, compute a checksum (by converting each byte to an integer and summing them), then write out the record and the checksum and go on to the next. I think I'm stumbling on to a signed/unsigned problem.

I open the file and read the entire contents into a Byte Array that I then convert to a String:

DataInputStream in=new DataInputStream(new FileInputStream(fin));
int nbytread=in.read(datain,0,flen);
String datast = new String(datain);

I then have a loop defining the start and stop substring addresses in the string, get the substring representing the pertinent record ...
String tstr = datast.substring(add1,add2);
and pass it to a checksum method:
int cs=compCS(tstr);

I think that's going ok. My problem seems to be inside the checksum method where I convert the string (1 character at a time) to and integer:

public static int compCS (String hstr) {
int slen = hstr.length();
int chsm = 0;
for (int i=0; i<slen; i++) {
char hc = hstr.charAt(i);
int tempint=(int)hc;
//tempint= (tempint + 0x10000 ) % 0x10000;
chsm += tempint;
System.out.print(&quot;int@char: &quot;+tempint+&quot;; &quot;);
}
return chsm;
}
the converted integer gets squirrely at 127 (when the msb goes to 1). Is there a way to do this?

Bob Rashkin
rrashkin@csc.com
 
Don't know if this will help:

Code:
public static long checksum( String sin){

	long lret = 0;
	byte[] byt = sin.getBytes();
	for( int n=0; n<byt.length; n++)
		lret += byt[n];

	return lret;
}

-pete
 
Thanks. That was great. Bob Rashkin
rrashkin@csc.com
 
I spoke to soon. It's still treating bytes with a &quot;1&quot; in the most significant bit as negative numbers. How do I make them unsigned bytes? Bob Rashkin
rrashkin@csc.com
 
Bob, your right! my bad, try this:
Code:
public static long checksum( String s){
	long lret = 0;
	byte[] byt = sin.getBytes();
	for( int n=0; n<byt.length; n++)
	  lret += (long)(byt[n] & 0xff);

	return lret;
}

-pete
 
Thanks Bob Rashkin
rrashkin@csc.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top