提取 3 个字节到一个数字
Extracting 3 bytes to a number
最快的方法是什么,使用位运算符 return 数字,用 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 的幂。
假设您知道系统的字节序(这里假设是小字节序),最快的方法是直接内存写入:
unsigned char byte1 = 200;
unsigned char byte2 = 40;
unsigned char byte3 = 33;
unsigned long number = 0;
((unsigned char*)&number)[0] = byte1;
((unsigned char*)&number)[1] = byte2;
((unsigned char*)&number)[2] = byte3;
或者,如果您不介意做一些运动,您可以这样做:
union
{
unsigned long ulongVal;
unsigned char chars[4]; // In case your long is 32bits
} a;
然后赋值:
a.chars[0] = byte1;
a.chars[1] = byte2;
a.chars[2] = byte3;
a.chars[3] = 0;
您将从 a.ulongVal
中读取最终值。这将节省额外的内存操作。
最快的方法是什么,使用位运算符 return 数字,用 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 的幂。
假设您知道系统的字节序(这里假设是小字节序),最快的方法是直接内存写入:
unsigned char byte1 = 200;
unsigned char byte2 = 40;
unsigned char byte3 = 33;
unsigned long number = 0;
((unsigned char*)&number)[0] = byte1;
((unsigned char*)&number)[1] = byte2;
((unsigned char*)&number)[2] = byte3;
或者,如果您不介意做一些运动,您可以这样做:
union
{
unsigned long ulongVal;
unsigned char chars[4]; // In case your long is 32bits
} a;
然后赋值:
a.chars[0] = byte1;
a.chars[1] = byte2;
a.chars[2] = byte3;
a.chars[3] = 0;
您将从 a.ulongVal
中读取最终值。这将节省额外的内存操作。