The C# code is exactly the equivalent of the C code, mind to explain what
problem you have with it?
Willy.
| Willy,
| I am trying to turn the afformentioned code into c#.
| Nicolas gave me some c# code that was supposed to do it, but it breakes
| down at i_data= (WORD*)data. The code i was given is:
|
| public ushort CalcChecksum(byte[] data, ushort length)
| {
| // The return value.
| ushort retVal = 0;
|
| // Cycle through the bytes.
| for (ushort index = 0; index < length / 2; ++index)
| {
| // Get the current unsigned short.
| ushort current = BitConverter.ToUInt16(data, index * 2);
|
|
| // Alter the checksum.
| retVal ^= current;
| }
|
|
| // Return the checksum.
| return (ushort) (retVal ^ 0xffff);
|
|
|
| }
|
| If you can see the problem I'd appreciate it.
| Thanks
| Mike
|
|
| Willy Denoyette [MVP] wrote:
| > | > |I was, and am still thinking that:
| > | i_data= (WORD*)data;
| > |
| > | converts it into a ushort.
| > |
| > Sure but with the cast you pretend that you are pointing to a WORD, that
| > means that you take both data[0] AND data[1] and vove it to an WORD.
That
| > means if data[0] = 128 (0x80) and data[1] = 24 (0x18). the result i_data
| > hold 0x8018 after the move (that's 6272 on intel achitectures).
| >
| > | Here is the c:
| > |
| > | WORD calcChecksum(BYTE data[], WORD length)
| > | /* Calculates a checksum of "data".
| > | */
| > | {
| > | WORD* i_data;
| > | WORD checksum= 0;
| > | BYTE i= 0;
| > |
| > | i_data= (WORD*)data;
| > |
| > | for (i= 0; i < length/2; i++)
| > | {
| > | checksum^= i_data
; /* xor-ing */
| > | }
| > | return(checksum ^ 0xffff); /* inverting */
| > | }
| > | return (ushort)(checksum ^ 0xffff);
| > |
| > |
| > |
| > | }
| > |
| > |
| > | As I run this through Visual Studio, that particular statement(
i_data=
| > | (WORD*)data turns i_data to 6272. But data is 128.
| > |
| >
| > That's correct (assumed data[1] = 0x18, what did you expect?
| >
| > | One more thing that may be inportant:
| > | There is 2 typedefs
| > | typedef unsigned char BYTE;
| > | typedef unsigned short WORD;
| > |
| > | I dont know how inportant they are. Is there a difference between a
| > | byte and an unsigned char?
| >
| > No. the types says threat BYTE as an unsigned char in code.
| > But, where is the C# question in this posting, I would suggest you to
post
| > to a C language NG like microsoft.public.dotnet.languages.vc.
| >
| > Willy.
|