How can I replicate Perl's unpack functionality in C#?

I am trying to recreate a Perl script in C# but have a problem creating a checksum value that a target system needs.

In Perl this checksum is calculated using the unpack function:

while (<PACKAGE>) {
    $checksum += unpack("%32C*", $_);
$checksum %= 32767;

where PACKAGE is the .tar file input stream

I need to replicate this in C# but can't find a means of replicating that unpack function.

All help appreciated!

(I know there are much better checksum calculations available but can't change target system so can't change calculation)


There seems to be a library in Mono called DataConvert that was written to provide facilities similar to Perl's pack/unpack. Does this do what you need?

Perkl's unpack is described here and here. From that you should be able to write an equivalent in C#.

To supplement Mitch Wheat's comment, here's a Java implementation (which does a single block only). I'm sure you'll find a way to convert it into C#, and to do multiple blocks.

int sum = 0;
for (byte b : buffer) {
    sum += (int) b & 255;
return sum % 32767;

Hope this helps!

In my testing here, unpack with %32C appears to be the additive sum of the bytes, limited to 32 bits.

print unpack("%32C*", 'A');
print unpack("%32C*", 'AA');

It shouldn't be hard to reproduce that.

Based on the comments of Chris Jester-Young and piCookie, I developed the following function. I hope you find it useful.

int fileCheckSum(const char *fileName)
   FILE *fp;
   long fileSize;
   char *fileBuffer;
   size_t result;
   int sum = 0;
   long index;

   fp = fopen(fileName, "rb");
   if (fp == NULL)
      fputs ("File error",stderr); 
      exit (1);

   fseek(fp, 0L, SEEK_END);
   fileSize = ftell(fp);
   fseek(fp, 0L, SEEK_SET);

   fileBuffer = (char*) malloc (sizeof(char) * fileSize);   
   if (fileBuffer == NULL)
      fputs ("Memory error",stderr);
      exit (2);

   result = fread(fileBuffer, 1, fileSize, fp);   
   if (result != fileSize)
      fputs ("Reading error", stderr);
      if (fileBuffer != NULL)

      exit (3);

   for (index = 0; index < fileSize; index++)
      sum += fileBuffer[index] & 255;

   if (fileBuffer != NULL)

   return sum % 32767;  

Need Your Help

Can't seem to get PHP form to display

php post

I am working on my version 2 of my portfolio site, I had a working mailer I created with a guide about a year ago, transferred it, and can't get my page to display now.

Can any mobile automation tool work on current device session?

android selenium-webdriver appium monkeyrunner

I am working on an android app, which has two user flows. Let's call them flow A and B !! Now, flow B is dependent on flow A, means flow B can only be performed after flow A. And, if user performs ...