0

I'm using libpcap to analyze and process packets. I have to compare two arrays of unsigned chars, take the difference and save it to a hashtable. Another thread will periodically scans across the hashtable and compute for average,standard deviation, max and min.

My question is the following, what would be the most efficient way to perform subtraction on two arrays?

For example:

A="0x34 0x44 0x59 0x5B"
B="0x34 0x42 0x43 0x43"

My first thought is to convert it to an integer, by converting the array into an array of signed chars, doing take requires a function to perform lookup function. Because this is function is called for every packet received on the system.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
user2066671
  • 177
  • 4
  • 16
  • 2
    Why are you storing the values in a hash table if what you want to do with them is to compute average, standard deviation, max and min? For none of these operations will a hash table be the most efficient data structure. A contiguous array will be much better. – 5gon12eder Jan 20 '15 at 05:53
  • How about converting both packet's data to sets and using http://www.cplusplus.com/reference/algorithm/set_difference/ – Sameer Naik Jan 20 '15 at 05:57
  • Not quite sure I follow. Are these long arrays? Or fixed length? Are you wanting to subtract the individual bytes or reinterpret the bytes as a longer integer? – Chris Jan 20 '15 at 06:06
  • The reason for a hash table is also because I need to key on certain patterns, and there is an array associated with each key. But you are right, if the pattern variations arenlow, I can use a n x m array, it will be much faster – user2066671 Jan 20 '15 at 07:01

1 Answers1

1

use the union can make this simple, because different data types share the same memory, we can then use this feature to convert data type.

note the Little-endian

#include <stdio.h>

typedef union new_array{
    struct array {
        unsigned char f4;
        unsigned char f3;
        unsigned char f2;
        unsigned char f1;
    }array;
    unsigned int int_array;
}new_array;

int main()
{
    new_array A, B;
    A.array.f1 = 0x34;
    A.array.f2 = 0x44;
    A.array.f3 = 0x59;
    A.array.f4 = 0x5B;

    B.array.f1 = 0x34;
    B.array.f2 = 0x42;
    B.array.f3 = 0x43;
    B.array.f4 = 0x43;

    printf("%u\n", A.int_array - B.int_array);
}
simon_xia
  • 2,394
  • 1
  • 20
  • 32