Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

CRC calculations and endian'ness

 
Aaron Roberts
Ranch Hand
Posts: 174
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've been working on an app which parses files and interprets the data as littleEndian format. If the file contains a CRC in it, I can convert the bytes to bigEndian format for use in java, but what about the CRC routine itself? Does a CRC routine result depend upon the endian'ness of the machine its running on? I'm assuming the CRC routine to be fed with byte values.
 
don cline
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aaron,
The byte order of a file does effect the CRC. I've been using CRC32.
The following is a program that calculates the CRC32 from a file, try it out yourself:
---------------------------------------------------------------------------
import java.util.*;
import java.io.*;
import java.util.zip.*;
public class CalculateChecksumFromFile
{
static public void main(String[] args)
{
System.out.println("CalculateChecksum");
String fileContents = "";

if (args.length < 1)
{
System.out.println("Use: java CalculateChecksumFromFile <Filename>");
}
System.out.println("Calculating checksum for:"+args[0]);

File currentFile = new File(args[0]);
try
{
FileReader fR;
fR = new FileReader(currentFile);
char[] buff = new char[16*1048576];
int readChars = fR.read(buff);
while (readChars > 0)
{
fileContents = fileContents + (new String(buff,0,readChars));
readChars=fR.read(buff);
}
fR.close();
}
catch (IOException iOE)
{
System.out.println("Exception:"+iOE.toString());
return;
}
byte[] byteArray = (fileContents).getBytes();
byte[] buffer = new byte[8192];
ByteArrayInputStream bAIS = new ByteArrayInputStream(byteArray);
CRC32 cRC32 = new CRC32();
CheckedInputStream cIS = new CheckedInputStream(bAIS, cRC32);
int byteRead = 0;
try
{
while (byteRead != -1) byteRead = cIS.read(buffer, 0, buffer.length);
}
catch (IOException iOE)
{
System.out.println("IOException:"+iOE.toString());
}
String calcChecksum = Long.toHexString(cIS.getChecksum().getValue());
System.out.println("Checksum is :"+calcChecksum);
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic