c - 在没有 btsl 指令的情况下使用 inline asm 设置位
问题描述
我想在位置 p 设置一点,而不使用 btsl 指令和内联 asm gcc c 代码。使用 btsl 指令很简单:
int n,p;
scanf("%d%d",&n,&p);
asm("btsl %1, %0"
:"=m"(n)
:"Ir"(p)
:"cc");
我知道设置位可以做到:
n|=1<<p;
现在,我正在使用内联 asm 这样做:
asm("movl %1, %%eax;"
"movl %2, %%ebx;"
"shl $1, %%ebx;"
"orl %%ebx, %%eax;"
"movl %%eax, %0;"
:"=b"(n)
:"a"(n), "b"(p)
:"cc");
printf("%d\n",n);
在我看来 shl 指令不起作用。例如 n=20=10100。当我尝试设置第一位 p=1 时,结果是 22=10110 而不是 21=10101
解决方案
按照迈克尔的例子,我已经完成了 clear 和 toggle 以及设置:
unsigned long bitset(unsigned long value, uint8_t shift)
{
unsigned long tmp;
asm ("mov $0x1, %[tempreg]\n\t"
"shl %[shift], %[tempreg]\n\t"
"or %[tempreg], %[val]"
: [val]"+r"(value),
[tempreg]"=&r"(tmp)
: [shift]"cN"(shift));
return value;
}
unsigned long bitclear(unsigned long value, uint8_t shift)
{
unsigned long tmp;
asm ("mov $0x1, %[tempreg]\n\t"
"shl %[shift], %[tempreg]\n\t"
"not %[tempreg]\n\t"
"and %[tempreg], %[val]\n\t"
: [val]"+r"(value),
[tempreg]"=&r"(tmp)
: [shift]"cN"(shift));
return value;
}
unsigned long toggle(unsigned long value, uint8_t shift)
{
unsigned long tmp;
asm ("mov $0x1, %[tempreg]\n\t"
"shl %[shift], %[tempreg]\n\t"
"xor %[tempreg], %[val]"
: [val]"+r"(value),
[tempreg]"=&r"(tmp)
: [shift]"cN"(shift));
return value;
}
推荐阅读
- python-3.x - “无法为任何语言加载 Spacy 模型:en”在本地运行良好,但在 heroku 上部署时出现问题
- javascript - React:从另一个组件调用时,字符串自动转换为 [object promise]
- python - Python:当我使用 writerows(zip()) 时,我得到垂直文本
- ethereum - Chainlink 核心适配器路径问题:httpGet uint256 从 treasury.gov API 返回 0
- python - 从具有限制 Python 的列表中选择随机变量
- html - 在这种情况下我将如何使用引导程序?
- visual-studio-code - 通过 ss 将 vs 代码连接到 gcp cloudshell
- ssh - libgit2 是否支持 ssh 配置主机别名?
- go - Golang 频道缺少一些值
- deep-learning - 增量神经网络训练