Wireshark-dev: Re: [Wireshark-dev] need to read three bytes of offset
From: Jakub Zawadzki <darkjames@xxxxxxxxxxxxxxxx>
Date: Thu, 4 Mar 2010 23:35:41 +0100
> Oh, then it looks correct to write a function that reads 3 bytes int value
> from pacp / wire and convert it to an int? This is what I have done: I read
> the three bytes from the pcap in to an array of three bytes. And then I
> memcpy these 3 bytes from array to an int variable(which has been memset
> with 0's) And then I do a ntohl on this int variable and return it as an
> int.

Some code:

#include <stdio.h>
#include <string.h>
#include <netinet/in.h>

int main() {
    unsigned char buf[3] = { 0x01, 0x02, 0x03 };
    unsigned int val;
    unsigned int proper;

/* your code if I understood it correctly... */
    memset(&val, 0, sizeof(val));
    memcpy(&val, buf, sizeof(buf));
    val = ntohl(val);
    printf("%10d %.8x\n", val, val);

/* easier one :) */
    proper = buf[0] << 16 | buf[1] << 8 | buf[2];
    printf("%10d %.8x\n", proper, proper);

    return 0;
}

results on LE machine:
#v+
  16909056 01020300 (16909056 >= 2^24 -- doesn't fit in 3 bytes!!!)
     66051 00010203
#v-

If you need also signed int24, you need to do more stuff :) (expand sign?)


Btw. It's *wireshark*-dev list, why do you ask C/pcap related questions here?
I think there're lot more approporiate newsgroups for these kind of questions.

We would avoid confusion, when you ask question and you're getting reply how to do things in wireshark api :)

Cheers.