0

I have a unsigned short buffer , it contain a hexa values of IP header .

unsigned short buffer = {45,00,00,4E,4E,05,00,10,80,11,0X00,0X00,0A,00,00,1C,1A,00,00,2F};

I added 0X00 , 0X00 in the place of Checksum filed and calculated checksum with the RFC 1071 - Calculating IP header checksum . So it is returning a unsigned short checksum value . Now i need to insert to the Ip buffer .

For example : if my unsigned short checksum value = 55168 and it's Hex value = D780 . Now i need to add D7 , 80 to buffer[11] and buffer[12] . How can i convert unsigned short checksum value and split the Hex value for inserting to the buffer ? If it Hex = D78 , then also i need to add 0D and 78 to the buffer field .

user2986042
  • 1,098
  • 2
  • 16
  • 37
  • You have a buffer which holds 20 elements of type `unsigned short`. But a single `unsigned short` takes 2 elements of it? Shouldn't your buffer be of type `unsigned char`? – Gerhardh Apr 05 '17 at 08:22
  • Not to mention that you have tons of invalid tokens. `4E` or `0A` are not valid tokens. You need `0x4E`, `0x0A`, etc. – Gerhardh Apr 05 '17 at 08:24

2 Answers2

1

You can separate the values using the bit operators

buffer[11] = (checksum >> 8) & 0xff;
buffer[12] = checksum & 0xff;

The first line shifts the checksum by 8 bits to the right, which is equivalent to dividing by 256 and than ensures, that you only get the information of those remaining 8 bits (0xD7) by using the and(&) operator with 0xff which equals to 1111 1111 in binary representation. The second line also uses the and operator to save ONLY the last 8 bit of your checksum, which would be 0x80.

Aeonos
  • 365
  • 1
  • 13
1

You can use expressions of the form buffer[11] = (checkSum & 0xFF00) >> 8; buffer[12] = (checkSum & 0xFF), but you should carefully check if your processor architecture uses big endian or little endian form for representing integers. Hence, it may be that on some systems you have to exchange the expressions to buffer[12] = (checkSum & 0xFF00) >> 8; buffer[11] = (checkSum & 0xFF).

See the following code:

#include <stdio.h>

unsigned short getCheckSum(unsigned short buffer[]) {
    return 0xD780;
}

int main(int argc, const char *argv[])
{
    unsigned short buffer[20] = {0x45,0x00,0x00,0x4E,0x4E,0x05,0x00,0x10,0x80,0x11,0X00,0X00,0x0A,0x00,0x00,0x1C,0x1A,0x00,0x00,0x2F};

    unsigned short checkSum = getCheckSum(buffer);

    buffer[11] = (checkSum & 0xFF00) >> 8;
    buffer[12] = (checkSum & 0xFF);

    for (int i=0; i<20; i++) {
        printf("%02X ", buffer[i]);
    }

    return 0;
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58