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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With