tags:

views:

1180

answers:

4

Hi,

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;
close(PACKAGE);

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)

+5  A: 

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?

Adam Bellaire
The OP has spammed the internet with this question. Clearly he is not looking for answers as I already suggested your advice to him on CodeProject.
leppie
unfortunately I cannot install the dataconvert library on the server we are using so I am looking for alternatives. I wouldn't say asking the question on 7 forums is spamming the internet-my assumption was that each forum would have different readers and I would get different responses from each..
+3  A: 

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

Mitch Wheat
+3  A: 

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!

Chris Jester-Young
A: 

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

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

It shouldn't be hard to reproduce that.

piCookie
yeah, the problem I seem to have is because the file is a tar it has non-standard ascii characters in there and these throw up different results in the perl script and the C# script I put together. Just can't determine why.
Are you ensuring binary mode in both cases? Regardless of the "tar" type of file format, reading one byte at a time in binary (non-translated or non-ASCII) mode should give the same bytes regardless of the language.
piCookie