epo*_*pok 4 c++ bit-manipulation
这是我的C++函数,它使用一种按位:
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;
}
Run Code Online (Sandbox Code Playgroud)
我正在使用它来生成密钥(对象的唯一值).
可以传递给函数的值的范围是:对于参数=> [0..255],对于b参数=> [0..127]和对于c参数=> [0..127].
假设只能使用相同的三个参数值调用该函数一次.例如,只有一个调用值(10,0,0).
函数是否返回重复值?
谢谢.
您的函数可能会为每组唯一的输入值返回唯一值(假设您的值int至少为24位).但是,更好的方法是写这个:
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);
}
Run Code Online (Sandbox Code Playgroud)
这将三个8位值组合成一个24位值,而不使用难以读取的指针操作.
请注意,在移动它们之前,我已经注意将char值(可能signed char取决于您的编译器设置)unsigned char转换为.原因是转移将首先将价值提升为已签署的int,这可能涉及签署延期.你不会想要的.