How can I replicate Perl unpack functions in C #?

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

In Perl, this checksum is calculated using the unpack function:

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

where PACKAGE is the input stream of the .tar file

I need to replicate this in C #, but cannot find a means to replicate this unpack function.

All help appreciated!

(I know that there are much better checksum calculations, but they cannot change the target system, so you cannot change the calculation)

+4
source share
5 answers

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

+6
source

Perkl unpack is described here and here . From this, you should be able to write the equivalent in C #.

+4
source

To add a comment to Mitch Wheat, a Java implementation is implemented here (which makes only one block). I am sure that you will find a way to convert it to C # and make a few blocks.

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

Hope this helps!

+4
source

In my testing here, unpacking with% 32C is an additive sum of bytes limited to 32 bits.

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

Unable to reproduce this.

0
source

Based on the comments of Chris Jet-Young and piCookie, I developed the following function. I hope you find this helpful.

 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) free(fileBuffer); exit (3); } for (index = 0; index < fileSize; index++) { sum += fileBuffer[index] & 255; } fclose(fp); if (fileBuffer != NULL) free(fileBuffer); return sum % 32767; } 
0
source

Source: https://habr.com/ru/post/1277559/


All Articles