C ++ function using bitwise type: will I get duplicate values?

this is my C ++ function that uses the bit type:

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 use this to generate keys (unique value for the object).

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

Suppose a function can only be called once with the same three argument values. For example, there will be only one call with values ​​(10, 0, 0).

Does the function return duplicate values?

Thanks.

+4
source share
3 answers

Your code will give different results for different architectures. Maybe it doesn’t matter, of course.

This is the portable equivalent:

 return ((((int) a << 8) + b) << 8) + c; 

Or that:

 return ((((int) a * 256) + b) * 256) + c; 
+1
source

Your function probably returns unique values ​​for each unique set of input values ​​(assuming your int has a width of at least 24 bits). However, it is best to write this:

 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 one 24-bit value without using difficult to read pointer manipulations.

Please note that I made sure to give char values ​​(which may be signed char depending on your compiler options) to unsigned char before porting them. The reason is that the shift will first push the value to the signed int , which may include character expansion. You do not want this.

+7
source

On any intelligent machine that can think of unique input values, you will get a unique result.

0
source

All Articles