简体   繁体   English

从 C 中的二进制“组件”构造一个 int

[英]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.我在 C 中对此进行编程,这对我来说是一种新语言。

So let's say my equations return Y0 = 1 , Y1 = 0 and Y2 = 1 ( 101 );所以假设我的方程返回Y0 = 1Y1 = 0Y2 = 1 ( 101 ); I want to store that value as 5 .我想将该值存储为5

Is this possible in C if these values are returned by different equations?如果这些值由不同的方程返回,这在 C 中是否可行?

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.我知道如何通过乘法来做到这一点,但我正在寻找 function 或我想已经内置在 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. C标准库中没有这样的function。

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.因此,在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;
}

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.它取决于您定义位的顺序,匹配该机器上 integer 的位/字节顺序。 So, there is a way to do it without bit shifting, but you're almost certainly better off going with the bit shifting solution.因此,有一种方法可以在不进行位移的情况下做到这一点,但几乎可以肯定的是,使用位移解决方案会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM