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("int@char: "+tempint+"; "
}
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
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("int@char: "+tempint+"; "
}
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