给定n比特的位串,将它分成两半的优雅方式是什么,比如左n / 2位和右n / 2位。
例如13是4位1101,输出应该是L = 3(11)并且R = 1(01) 优选在C(甚至伪代码很好)
答案 0 :(得分:0)
请参阅以下伪代码。这适用于32位输入。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define USERSIZE 128
long long int bin2dec(long long int ip)
{
int count, calc;
long long int add = 0;
for (count = 0; count < 64; count++)
calc = ip%10;
add += pow(2, count) * calc;
ip = ip/10;
if (ip == 0) break;
}
return add;
}
int main()
{
int len = -1, maskval = -1;
long long int temp;
long long int intLeft;
long long int intRight;
char * input, *left, *right;
input = calloc (USERSIZE, sizeof *input);
left = calloc (USERSIZE/2, sizeof *left);
right = calloc (USERSIZE/2, sizeof *right);
printf("Enter the number in binary\n");
scanf("%s", input);
len = strlen (input);
if (len> 0)
{
if (len%2 == 0)
{
maskval = len/2;
strncpy(left, input, maskval);
temp = atoll(left);
intLeft = bin2dec(temp);
printf("left = %lld (%lld)\n", intLeft, temp);
input += maskval;
strncpy(right, input, maskval);
temp = atoll(right);
intRight = bin2dec(temp);
printf("right = %lld (%lld)\n", intRight, temp);
}
else
printf("This number does not have even number of bits, pleease add a 0 before the number and enter again\n");
}
else
printf("Enter a valid string\n");
return 0;
#endif
}
[sourav@infba01383 so_overflow]# ./a.out
Enter the number in binary
100
This number does not have even number of bits, pleease add a 0 before the number and enter again
[sourav@infba01383 so_overflow]# ./a.out
Enter the number in binary
0100
left = 1 (1)
right = 0 (0)
[sourav@infba01383 so_overflow]# ./a.out
Enter the number in binary
1000
left = 2 (10)
right = 0 (0)
[sourav@infba01383 so_overflow]# ./a.out
Enter the number in binary
0000
left = 0 (0)
right = 0 (0)
[sourav@infba01383 so_overflow]# ./a.out
Enter the number in binary
1111
left = 3 (11)
right = 3 (11)
[sourav@infba01383 so_overflow]#./a.out
Enter the number in binary
11111111111111111111111111111111
left = 65535 (1111111111111111)
right = 65535 (1111111111111111)
[sourav@infba01383 so_overflow]#
小心!没有检查输入的有效性。