C中的按位运算

时间:2011-09-28 02:02:01

标签: c bit-manipulation

我正在进行C编程分配,我需要模拟3位解码器的操作。我的编译器抱怨,这篇维基百科文章给出了一个C运算符列表,但我的代码似乎仍然无法正常工作。

维基百科:http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Bitwise_operators

编译错误:

logic.c: In function ‘three_bit_decoder’:
logic.c:33: warning: statement with no effect
logic.c:33: error: expected ‘;’ before ‘~’ token
logic.c:34: warning: statement with no effect
logic.c:34: error: expected ‘;’ before ‘b0’
logic.c:35: warning: statement with no effect
logic.c:35: error: expected ‘;’ before ‘~’ token
logic.c:36: warning: statement with no effect
logic.c:36: error: expected ‘;’ before ‘b0’
logic.c:38: warning: statement with no effect
logic.c:38: error: expected ‘;’ before ‘b0’
logic.c:39: warning: statement with no effect
logic.c:39: error: expected ‘;’ before ‘b0’
logic.c:40: warning: statement with no effect
logic.c:40: error: expected ‘;’ before ‘~’ token
logic.c:41: warning: statement with no effect
logic.c:41: error: expected ‘;’ before ‘b0’
logic.c:43: warning: return makes integer from pointer without a cast
logic.c:43: warning: function returns address of local variable
make: *** [logic.o] Error 1

代码:

int three_bit_decoder(BIT b0, BIT b1, BIT b2) {
    /* Returns an 8 bit number, by 2^3
     * 
     */
        int myIntDecoder[8]; 

        myIntDecoder[0] ~b0 + ~b1 + ~b2;
        myIntDecoder[1] b0 + ~b1 + ~b2;
        myIntDecoder[2] ~b0 + b1 + ~b2;
        myIntDecoder[3] b0 + b1 + ~b2;

        myIntDecoder[4] b0 + ~b1 + ~b2;
        myIntDecoder[5] b0 + ~b1 + b2;
        myIntDecoder[6] ~b0 + b1 + b2;
        myIntDecoder[7] b0 + b1 + b2;

        return myIntDecoder;
}

4 个答案:

答案 0 :(得分:4)

如果这些是作业陈述,那么你就会错过相同的符号。

myIntDecoder[0] = ~b0 + ~b1 + ~b2;
myIntDecoder[1] = b0 + ~b1 + ~b2;
myIntDecoder[2] = ~b0 + b1 + ~b2;
myIntDecoder[3] = b0 + b1 + ~b2;

myIntDecoder[4] = b0 + ~b1 + ~b2;
myIntDecoder[5] = b0 + ~b1 + b2;
myIntDecoder[6] = ~b0 + b1 + b2;
myIntDecoder[7] = b0 + b1 + b2;

您将遇到的下一个问题是int myIntDecoder[8]声明了一个包含8个int的数组,这与8位int不同。所有平台上的char都是8位宽;或者您可以更明确地使用标准typedef之一:

#include <stdint.h>

uint8_t myIntDecoder;

为了不让你感到茫然,我应该提到,为变量中的各个位分配并不像byte[5] = 1那么简单。这样做需要巧妙地使用移位和其他按位操作。

答案 1 :(得分:1)

按位运算符不是您的问题,您的代码中存在语法错误。考虑如何分配变量,解决方案应该来找你。

答案 2 :(得分:1)

据推测,你的目标是:

   myIntDecoder[0] = ~b0 + ~b1 + ~b2;
   // and likewise for the other 7 lines

但是尝试返回myIntDecoder无效。为此,您可能希望将数组移到函数外部(例如)将其地址传递给函数。

答案 3 :(得分:-3)

你错过了等于运算符。

myIntDecoder[7] = b0 + b1 + b2;

c中的not运算符也是!而非~