Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function using a kind of bitwise: I'll get duplicated values?

this is my C++ function that uses a kind of bitwise:

int genkey(const unsigned char a,const char b,const char c )
{
    int val=0;
    unsigned char *p= reinterpret_cast <unsigned char *>(&val);
    p[0]=a;
    char *q= reinterpret_cast <char *>(&val);
    q[1]=b;
    q[2]=c;
    return val;
}

I'm using that for generating keys (unique value for object).

The range of the values that can be passed to the function are: for a parameter => [0..255], for b parameter => [0..127] and for c parameter => [0..127].

Assume that the function can be called only once with the same three arguments values. For example there will be only one call with values (10, 0, 0).

Does function return duplicated values?

Thanks.

like image 560
epok Avatar asked Feb 25 '23 20:02

epok


1 Answers

Your function probably returns unique values for each unique set of input values (assuming your int is at least 24 bits wide). However, a better way to write this might be:

int genkey(const unsigned char a,const char b,const char c )
{
    return a
         | (static_cast<unsigned char>(b) << 8)
         | (static_cast<unsigned char>(c) << 16);
}

This combines three 8-bit values into a single 24-bit value without using hard-to-read pointer manipulation.

Note that I have taken care to cast the char values (which might be signed char depending on your compiler settings) to unsigned char before shifting them. The reason is that shifting will first promote the value to a signed int, which may involve sign extension. You won't want that.

like image 66
Greg Hewgill Avatar answered Apr 29 '23 14:04

Greg Hewgill