c - 使用二元运算计算 n 个 1

标签 c binary numbers

有没有办法仅使用这些二元运算(n1!~&^、{1045)获取 |+ 67915 } , << ) 其中 >> 是输入?

示例,

n ---> output
0 ---> 0000
1 ---> 0001
2 ---> 0011
3 ---> 0111
4 ---> 1111
...

最佳答案

你可以这样做:

// Since "-" is not on your list while "+" is, I'll add negative 1
// using `~0`; this assumes that your computer uses 2's complement
// representation of negative numbers.
(1 << n) + ~0;

这个想法是 1 << n产生 2 的幂:1 , 10 , 100 , 1000 , 等等。添加一个负数产生 2^n-1 ,这就是您的模式所代表的内容。

关于c - 使用二元运算计算 n 个 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16189775/

相关文章:

c - 无符号和有符号数据比较及其在内存中的表示

Java 正则表达式 : Extracting a Version Number

perl - 如何在 Perl 中格式化特定于区域设置的数字?

c++ - 从二进制文件 C++ 读取行

c - 输入名称后,我的命令窗口崩溃了。 C

c - LibXML2 + 拉解析器 (stax) : stream position (ftell) of the event ?

C:改为argc和argv

c++ - 截断二进制数

javascript - 是否有任何 JS 全局函数可以将包含下划线作为数字分隔符的数字的字符串转换为数字?

c - 为什么这种奇怪的内存分配行为