Build int from binary "components" in C

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

I program this in C, which is a new language for me.

So let my equations come back Y0 = 1, Y1 = 0and Y2 = 1( 101); I want to keep this value as 5.

Is this possible in C if these values ​​are returned by different equations?

I know how to do this by multiplying, but I'm looking for a function or something that I think is already built into C.

+3
source share
4 answers

There is 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 */
+5
source

Just a bitdvig:

Y0 | (Y1 << 1) | (Y2 << 2)
+4
source

C .

:

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

, , , . , ideone , .

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;
}

, , , . , , / . , , .

+1

All Articles