c - 按位连接

标签 c bitwise-operators

我有以下内容:

char *pointer = decimal_to_binary(192) // yields 11000000
char *pointer2 = decimal_to_binary(168) // yields 10101000

我正在尝试将它们连接成:

1100000010101000

我引用的是:Concatenate binary numbers of different lengths目前正在使用:

unsigned long pointer3 = (*pointer << 16) | *pointer2;

给出输出:

1100010000000000110001

我做错了什么?

最佳答案

你没有展示你是如何打印任何东西的,这使得你的问题难以解释。然而,这个声明已经无可挽回地被破坏了,因为它没有连接 pointer 指向的字符串。和 pointer2 :

unsigned long pointer3 = (*pointer << 16) | *pointer2;

这需要第一个字符 pointer指向 (a 1) 并将值左移 16 位,然后在 pointer2 的第一个字符中添加 (ors)指向(另一个 1 ),并将这种格式的整数分配给错误命名的 pointer3 .因此,它获得了值(value):

pointer3 = 0x00310031;

这个问题需要一些解释,但是做出一些似是而非的(但不一定准确)的假设,这段代码可能会做你想要的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static char *decimal_to_binary(unsigned char byte)
{
    char *result = malloc(9);
    if (result != 0)
    {
        char *digit = result;
        for (int i = 0; i < 8; i++)
            *digit++ = ((byte >> (7 - i)) & 0x01) + '0';
        *digit = '\0';
    }
    return result;
}

int main(void)
{
    char *pointer1 = decimal_to_binary(192);
    char *pointer2 = decimal_to_binary(168);
    char  concatenated[17];
    unsigned long pointer3 = (*pointer1 << 16) | *pointer2;

    strcpy(&concatenated[0], pointer1);
    strcpy(&concatenated[8], pointer2);

    printf("P1 = <<%s>>; P2 = <<%s>>; P3 = 0x%08lX; C = <<%s>>\n",
           pointer1, pointer2, pointer3, concatenated);

    free(pointer1);
    free(pointer2);
    return(0);
}

输出:

P1 = <<11000000>>; P2 = <<10101000>>; P3 = 0x00310031; C = <<1100000010101000>>

请注意,代码使用 decimal_to_binary()没有注意避免(误)使用空指针。 decimal_to_binary()的设计也不如恒星;那些free()电话很容易被遗忘。更好的设计是:

void decimal_to_binary(unsigned char byte, char buffer[9]);

调用代码提供写入二进制输出的缓冲区。在 decimal_to_binary() 中还有其他编写循环的方法;有些甚至可能比此处选择的更有效率。

关于c - 按位连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16073943/

相关文章:

javascript - 为什么我需要一个位明智的运算符来访问最后一个数组元素?

java - 右操作数为负时位移运算符的行为

c - 对于 C,Visual Studio-2017 如何调试读取文本文件并在该文本文件后面打印输出的代码?

c - 如何验证 Linux radio 设备驱动程序中的 radio 频率?

c++ - 如何在 Eclipse 中将我的项目从多个编译单元转变为单个编译单元

c - "producing negative zeroes"在不支持的系统中是什么意思?

c - C 中的 5x5 矩阵乘法

c - "cannot convert to a pointer type"C

ios - 如何在 Swift 中创建 NS_OPTIONS 风格的位掩码枚举?

c - 无符号整数中的填充位和 C89 中的按位运算