C中的按位串联 [英] Bitwise concatenation in C

查看:87
本文介绍了C中的按位串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在C中连接两个二进制数.因此,如果我有10100011,我希望结果为10100011.我写了一个简短的例程,认为可以完成这项工作:

I'm trying to concatenate two binary numbers in C. So if I have 1010 and 0011 I want my result to be 10100011. I wrote a short routine that I thought would do the job:

#include <stdio.h>

int main(void) {
    int first = 1010;
    int second = 0011;
    int result = (first << 4) | second;
    printf("%d", result);
    return 0;
}

我知道打印的数字当然是十进制的,但是我发现按位运算后,我得到的十进制等效值为10100011或163.但是,我的结果打印为16169 .所以我想我的问题是...在这里我不理解其中的哪一部分?这仅仅是对printf的工作方式的误解,还是我的按位操作不正确?尝试使用int s执行此操作是否有问题?

I understand that the printed number of course is going to be in decimal, but I figured that after my bitwise operations I'd be getting the decimal equivalent of 10100011, or 163. However, my result is printed as 16169. So I guess my question is...what part of this am I not understanding here? Is it just a misunderstanding of how printf is working, or are my bitwise operations incorrect? Is it a problem to try to do this with ints?

推荐答案

您忘记了前缀0b,因此它应该对您有用:

You forgot the prefix 0b, so this should work for you:

#include <stdio.h>

int main() {

    int first = 0b1010;
              //^^v See here
    int second = 0b0011;
    int result = (first << 4) | second;
    printf("%d", result);

    return 0;

}

输出:

163

在您的示例中,二进制数"不是二进制数.第一个是普通的十进制数(1010),第二个是八进制数,因为有前缀0,所以在十进制中,第二个数字是:9

In your examle the 'binary numbers' aren't binary numbers. The first one is a normal decimal number (1010) and the second one is a octal number, because of the prefix 0 so in decimal the second number was: 9

所以发生了什么事

1010 -> decimal
0011 -> octal

第一个电话号码

First number:

     11 1111 0010      
----------------- << 4
11 1111 0010 0000

第二个数字(->十进制->二进制):

Second number (->decimal->binary):

  octal    decimal       binary
  0011  ->    9     ->  0000 1001

以及您的计算:

And your calculation:

11 1111 0010 0000   first number
             1001   second number
----------------- |
11 1111 0010 1001 = 16169

这篇关于C中的按位串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆