用位运算符返回用3个不同unsigned char
变量表示的数字的最快方法是什么?
unsigned char byte1 = 200;
unsigned char byte2 = 40;
unsigned char byte3 = 33;
unsigned long number = byte1 + byte2 * 256 + byte3 * 256 * 256;
是最慢的方法。
只需将每个移位到位,然后将它们或在一起:
#include <stdint.h>
int main(void)
{
uint8_t a = 0xAB, b = 0xCD, c = 0xEF;
/*
* 'a' must be first cast to uint32_t because of the implicit conversion
* to int, which is only guaranteed to be at least 16 bits.
* (Thanks Matt McNabb and Tim Čas.)
*/
uint32_t i = ((uint32_t)a << 16) | (b << 8) | c;
printf("0x%X\n", i);
return 0;
}
但是请注意,几乎所有现代编译器都将使用适当数量的位移来代替乘法乘以2的幂。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句