我在做循环右移和左移,我错了。对于右旋转,如果我给予输入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);
}
1条答案
按热度按时间deyfvvtc1#
代码假定
unsigned long
是32位。它的宽度必须 * 至少 * 为32位,但可以更大,如64。int
常量**1 << i
是移位的int
,但代码需要移位的unsigned long
。请使用1UL << i
。这意味着OP可能没有启用所有警告。节省时间。启用所有编译器警告。
一个wonderful way,用于获取整数类型的 * value * 位的位宽:
若要处理
[1 ... ULONG_WIDTH)
范围之外的n
,请减小偏移。