tra*_*day 2 c bit-manipulation
给定一个8位整数'c8',必须将位模式复制到32位整数'c32',这样'c32'由重复4次的'c8'组成.例如,
if c8 = 1000 1110,
then c32 = 1000 1110 1000 1110 1000 1110 1000 1110
Run Code Online (Sandbox Code Playgroud)
我已经考虑过这个并在C中提出了两种方法.但是,我不是那么经验,而且我不确定哪种方法,如果有的话,我应该在最终的代码中使用.
最小例子:
uint8_t c8 = 0b10001110; // for this example
// method 1
uint32_t c32 = ((c8 << 8 | c8) << 16) | (c8 << 8 | c8);
// method 2
uint16_t c16 = c8 << 8 | c8;
uint32_t _c32 = c16 << 16 | c16;
Run Code Online (Sandbox Code Playgroud)
这两种方法都按预期工作,但我想知道哪一种从专家的角度来看会更好":-).
在第一种方法中,我正在计算多个班次,而在第二个方法中,我正在创建一个额外的变量.我不是那种经验不足的低级事物(以及这些低级事物的表现),如果有人能指出我正确的方向,或者找到更好的方法,我会很感激.
谢谢.
最好是使用memset.一个好的编译器将其视为内在函数,并以尽可能最好的方式对其进行优化.我用GCC 6.3.0测试了以下程序,-O3
#include <stdio.h>
#include <inttypes.h>
#include <string.h>
int main(void) {
uint32_t target;
uint8_t byte;
// if we don't do this, GCC could just *fold the value as a constant*
scanf("%c", &byte);
memset(&target, byte, sizeof(target));
printf("%08" PRIX32 "\n", target);
}
Run Code Online (Sandbox Code Playgroud)
生成的机器代码实际上最终在我的平台上执行的操作类似于:
#include <stdio.h>
#include <inttypes.h>
#include <string.h>
int main(void) {
uint32_t target;
uint8_t byte;
scanf("%c", &byte);
target = 0x01010101UL * byte;
printf("%08" PRIX32 "\n", target);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |