C中的循环左右移位

qnzebej0  于 2023-01-08  发布在  其他
关注(0)|答案(1)|浏览(129)

我在做循环右移和左移,我错了。对于右旋转,如果我给予输入123和旋转数3,我得到的输出是错误的。请帮助我找到错误。

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

void rotateLeft(unsigned long int num,int n);
void rotateRight(unsigned long int num,int n);
void bin_print(unsigned long int num);

int main()
{
    printf("\tThis program is to circular right & left shift the int number by n\n\n");
    printf("Possible operations\n1. circular right shift\n2. circular left shift\n");
    int choice,n;
    unsigned long int num;
    printf("Enter your choice: ");
    scanf("%d",&choice);
    printf("Enter a number: ");
    scanf("%lu", &num);
    bin_print(num);
    printf("Enter number of rotation: ");
    scanf("%d", &n);
    (choice==1) ? rotateRight(num,n) : rotateLeft(num,n);
}

void bin_print(unsigned long int num)
{
    for(int i = 31; i >= 0; i--)
    {
        if((num & (1 << i))) {
            printf("%d",1);         // The ith digit is one
        }
        else {
            printf("%d",0);         // The ith digit is zero
        }
        if(i%8==0) printf(" ");
    }
    printf("\n");
}

void rotateLeft(unsigned long int num, int n)
{
    unsigned long int val = (num << n) | (num >> (32 - n));
    bin_print(val);
    printf("%ld",val);
}

void rotateRight(unsigned long int num,int n)
{
    unsigned long int val = (num >> n) | (num << (32 - n));
    bin_print(val);
    printf("%ld",val);
}
deyfvvtc

deyfvvtc1#

    • 不假设宽度**

代码假定unsigned long是32位。它的宽度必须 * 至少 * 为32位,但可以更大,如64。

    • int常量**

1 << i是移位的int,但代码需要移位的unsigned long。请使用1UL << i

    • 使用匹配的打印说明符**@支持乌克兰

这意味着OP可能没有启用所有警告。节省时间。启用所有编译器警告。

// printf("%ld",val);
printf("%lu",val);
#include <limits.h>

#if ULONG_MAX == 0xFFFFFFFFu
  #define ULONG_WIDTH 32
#elif ULONG_MAX == 0xFFFFFFFFFFFFFFFFu
  #define ULONG_WIDTH 64
#else
  #error TBD code
#endif

void bin_print(unsigned long int num) {
    // for(int i = 31; i >= 0; i--)
    for(int i = ULONG_WIDTH - 1; i >= 0; i--)
    ...

        // if((num & (1 << i))) {
        if((num & (1UL << i))) {
    • 高级**

一个wonderful way,用于获取整数类型的 * value * 位的位宽:

// https://stackoverflow.com/a/4589384/2410359
/* Number of value bits in inttype_MAX, or in any (1<<k)-1 where 0 <= k < 2040 */
#define IMAX_BITS(m) ((m)/((m)%255+1) / 255%255*8 + 7-86/((m)%255+12))

#define ULONG_WIDTH IMAX_BITS(ULONG_MAX)
    • 换档超过"32"**

若要处理[1 ... ULONG_WIDTH)范围之外的n,请减小偏移。

void rotateLeft(unsigned long num, int n) {
  // Bring n into (-ULONG_WIDTH ... ULONG_WIDTH) range,
  n %= ULONG_WIDTH;
  // Handle negative n.
  if (n < 0) n += ULONG_WIDTH;
  // Cope with 0 as a special case as `num >> (ULONG_WIDTH - 0)` is bad.
  unsigned long val = n == 0 ? n : (num << n) | (num >> (ULONG_WIDTH - n));
  bin_print(val);
  printf("%lu\n", val);
}

相关问题