gpt4 book ai didi

c - 提取 3 个字节到一个数字

转载 作者:太空宇宙 更新时间:2023-11-04 06:24:52 25 4
gpt4 key购买 nike

最快的方法是什么,使用位运算符返回数字,用 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 的幂。

关于c - 提取 3 个字节到一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28420352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com