Tag: 位操作

用于从H / W寄存器读取的位字段

我想从32位寄存器读取第2,第5和第6位。 我决定使用struct位字段来存储它们。 以下数据结构是否正确? struct readData { int unwanted:1; int reqbit1:1; int unwanted1:2; int reqbit2:2; int unwanted2:26; }; 我不确定如何创建位字段。 我将使用一个API,它将字节从h / w寄存器直接复制到此结构。 在那种情况下,reqbit1会包含第二位吗? 根据我的理解,编译器将第一位分配给一个int变量,第二位分配给另一个int变量,因此reqbit1将不会从寄存器中读取任何数据。 以下联盟不适合这种情况吗? union readData { struct readBits{ bool unwanted:1; bool reqbit1:1; xxx unwanted1:2; short reqbit2:2; xxx unwanted2:26; }; int regValue; }; 如果这是对的,我应该将不想要的2声明为什么?

使用0xffffffff按位和无符号长

下面是switch语句中的一些代码。 getvalue()返回unsigned long 。 有人可以解释为什么value与0xffffffff 。 mcu是32位。 #define WriteMemory(A,V) *(volatile unsigned long*)(A)=(V) static unsigned value; case ‘b’: value = getvalue(); value &= 0xffffffff; WriteMemory(2147455555, value); break;

C中的位移

如果对应于有符号整数的位模式向右移位 1 vacant bit will be filled by the sign bit 2 vacant bit will be filled by 0 3 The outcome is implementation dependent 4 none of the above 这个问题的答案是第三种选择..任何人都能解释一下这个问题, 还给出了一些基本思想,关于C编程中左移和右移算子背后的理论。 例如 当执行任何操作时,空位上填充的内容。 我检查并注意到左移将空位填充0并且右移填充1.请清除逻辑…

将9位值的流作为字节写入C中的文件

我有一个数组,其整数值从0-511(最多9位)。 我试图用fwrite写这个文件。 例如,使用数组: [257, 258, 259] Which is 100000001, 100000010, 100000011 I am trying to write 100000001100000010100000011 + extra padding of 0s to the file 但由于fwrite限制一次写入1个字节,我不知道该怎么做。 我是按位操作的新手,而不是如何分离各个字节。

使用按位运算最多三个整数?

如何仅使用按位操作返回最多三个无符号整数,例如!,〜,|,&,^,+,>>,<<。 我不知道从哪里开始。 任何帮助,将不胜感激。 编辑: 我只被允许使用给定的合法操作,就是这样。 /** maxOfThree – Returns the maximum of three integers. * NOTE: x, y, z are all in the range [0, TMax]. * Examples: maxOfThree(1, 2, 3) = 3 * Legal Ops: ! ~ & ^ | + <> * Max Ops: 25 int maxOfThree(int x, int y, int z) { […]

右移(分区) – > ROUND TOWARD ZERO

我这样做.. value >> 3; 它总是走向消极的一面。如何通过右移除法向零舍入?

返回x,其中n位从位置p开始,设置为y的最右边n位,其他位保持不变

我的解决方案 get the rightmost n bits of y a = ~(~0 << n) & y clean the n bits of x beginning from p c = ( ~0 << p | ~(~0 << (p-n+1))) & x set the cleaned n bits to the n rightmost bits of y c | (a << (p-n+1)) 这是一个相当长的陈述。 我们有更好的吗? […]

c中的hex到ASCII

这是我的逻辑,在C中将HEX转换为ASCII转换: for (i=0;i> 4; /*bit-shift the result to the right by four bits (ie quickly divides by 16)*/ if (char1 >9) { char1 = char1 – 0xa; char1 = char1 + ‘A’; } else char1 = char1 + ‘0’; Loc[j]=char1; j++; /*means use a bitwise AND to take the bottom four bits from the byte, […]

将1到32位数附加到char缓冲区

我有一个char*缓冲区,我想追加各种位大小( 1到32之间)的整数。 因此,我需要一个function: void addBits(char *buffer, int bits_appended_so_far, int object, int object_bit_size); 可以将13位的对象移动到缓冲区的第470位位置。 我当然可以将这些位逐个移到缓冲区,但速度至关重要,因此看起来应该可以一次移动更大的块。 有没有标准的方法来做到这一点? 似乎应该有一个标准的方法,但一些谷歌搜索和搜索没有给我我想要的东西。

使用XOR交换值

这两个宏有什么区别? #define swap(a, b) (((a) ^ (b)) && ((a) ^= (b) ^= (a) ^= (b))) 要么 #define swap(a, b) (((a) ^ (b)) && ((b) ^= (a) ^= (b), (a) ^= (b))) 我在这里看到了第二个宏但是不明白为什么它不像第一个那样写? 我错过了一个特殊原因吗?