开发者

Construct an int from binary "components" in C

I have several equations that will return the binary value for each of the three bits in my number.

I am programing this in C which is a new language for me.

So let's say my equations return Y0 = 1 , Y1 = 0 and Y2 = 1 (101); I want to store that value as 5.

Is this possible in C 开发者_JS百科if these values are returned by different equations?

I know how to do it by multiplying, but I am looking for a function or something which I imagine is already built into C.


No such luck. You have to multiply (or shift, which is the same)

unsigned Y0 = 1, Y1 = 0, Y2 = 1, val;

val = (Y0 * 4)  + (Y1 * 2)  + (Y2 * 1);  /* parens */
val = (Y0 << 2) + (Y1 << 1) + (Y2 << 0); /* redundant */


Just bitshift:

Y0 | (Y1 << 1) | (Y2 << 2)


There is no such function in the C standard library.

You will need to do:

int x = (Y2 << 2) | (Y1 << 1) | (Y0 << 0);


Although not very popular, you do have an alternative, in that you can use bit fields to perform the type of operation you're talking about. So, on ideone, the following code would perform the action you've suggested.

union combine {
    struct bits{
        int x: 1;
        int y: 1;
        int z: 1;
        int pad : 29;
    } bitvalues;
    int value;
};

int main() {
    union combine test;
    test.bitvalues.x = 1;
    test.bitvalues.y = 0;
    test.bitvalues.z = 1;
    test.bitvalues.pad = 0;
    printf("result: %d\n", test.value);
    return 0;
}

It's important to note however, that because you're using a combination of a bitfields and a union, this is not a portable solution. It is dependent on the order that you define your bits in, matching the bit/byte order for integer on that machine. So, there is a way to do it without bit shifting, but you're almost certainly better off going with the bit shifting solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜