首页 > 解决方案 > 如何用“y”位移“x”?

问题描述

我在使用移位程序时遇到了一些麻烦。

挑战在于编写一个程序,它可以将 unsigned int 向左移动数步。两个整数都由用户输入。因此,给定两个整数 (xy),其中的位xy向左移动,左侧丢失的位应向右移动。即,在最高有效位之外丢失的位被放置在最低有效位。

为了解决这个挑战,我做了以下尝试:

#include <stdio.h>
#include <utility.h>

unsigned int bitshift(unsigned int a, unsigned int b)
{
    a<<b;
    b>>a;
    return a,b; 
}

int main (void) 
{
    unsigned int x, y;
    
    printf("Enter two integers (smaller than 32) please:\n");
    scanf("%u%u", &x, &y);
    printf("Your integers are %u and %u.\n", x, y);
    printf("In hexadecimal-format, your integers are %08x and %08x.\n", x, y); 
 
    printf("We are now going to perform a bit shift operation\n");
    printf("The result of the bitshift operation is:\n");
    printf("%u and %u\n", bitshift(x,y));
    printf("In hexadecimal: %08x and %08x\n", bitshift(x,y));
    
    while(!KeyHit()); 
    return 0; 
    
}

但是,我在编译时收到一条错误消息,例如“参数不足”,我不明白。

但我最想知道的是该bitshift功能是否可以完成这项工作?

标签: cbit-manipulationbit

解决方案


这是对Barmar的(现已删除)功能解决方案的修改,bitshift并在评论中提出了改进建议。

不幸的是,C 没有像 CPU 指令集中可用的运算符来循环值中的位。这就是为什么可以通过将最低有效位向左移动,将最高有效位向右移动并组合结果来完成操作的原因。

要计算将最高有效位向右移动的移位宽度,必须使用 来计算数据类型中的位数sizeof

请注意,大于或等于值中位数的移位宽度是未定义行为 (UB)。这就是为什么移位宽度是以值中的位数为模来计算的。此外,左移 0 将导致右移中的 UB。

#include <stdio.h>
// get CHAR_BITS to make code portable for unusual platforms
#include <limits.h>

unsigned int bitshift(unsigned int a, unsigned int b)
{
    // modulo operation to prevent undefined behavior
    b %= sizeof a * CHAR_BIT; // sizeof a * 8 on usual platforms
    // prevent undefined behavior for right shift
    if(b == 0) return a;

    unsigned int upper = a << b;
    // not portable for unusual platforms
    // unsigned int lower = a >> (sizeof a * 8 - b);
    unsigned int lower = a >> (sizeof a * CHAR_BIT - b);
    
    return upper | lower;
}

int main (void) 
{
    unsigned int x, y;
    
    printf("Enter two integers (smaller than 32) please:\n");
    scanf("%u%u", &x, &y);
    printf("Your integers are %u and %u.\n", x, y);
    printf("In hexadecimal-format, your integers are %08x and %08x.\n", x, y); 
 
    printf("We are now going to perform a bit shift operation\n");
    printf("The result of the bitshift operation is:\n");
    printf("%u\n", bitshift(x,y));
    printf("In hexadecimal: %08x\n", bitshift(x,y));
    
    return 0; 
    
}

示例输入/输出:

Enter two integers (smaller than 32) please:
1234567890 12
Your integers are 1234567890 and 12.
In hexadecimal-format, your integers are 499602d2 and 0000000c.
We are now going to perform a bit shift operation
The result of the bitshift operation is:
1613571225
In hexadecimal: 602d2499
Enter two integers (smaller than 32) please:
246 28
Your integers are 246 and 28.
In hexadecimal-format, your integers are 000000f6 and 0000001c.
We are now going to perform a bit shift operation
The result of the bitshift operation is:
1610612751
In hexadecimal: 6000000f

推荐阅读