Hi guys this is my first post in here and I hope to be an active user
I got some problems with this code.
It is supposed to rotate of n_bit the input char and print the bit rappresentation
Now here is the not working code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
char rotate_c(char c, short n_bit);
void arr_bit (short arr[], char c);
int main() {
char c;
char c_rot;
short n, arr[8], arr_rot[8];
printf("Insert char\n-> ");
c = getchar();
printf("%c = ",c);
arr_bit(arr,c);
for (n = 0; n < 8; n++)
printf("%d",arr[n]);
printf("\n [(-7,-1)(1-7)]\n-> ");
scanf("%d", &n);
c_rot = rotate_c(c,n);
printf("Your char: %c\n", c);
printf("modified: %c\n", c_rot);
arr_bit(arr_rot,c_rot);
for (n = 0; n < 8; n++)
printf("%d",arr_rot[n]);
}
char rotate_c(char ch, short n_bit) {
char car = ch;
char temp;
if (n_bit < 0) {
n_bit = abs(n_bit);
temp = car;
car = car<<n_bit;
temp = temp>>(8-n_bit);
car = car|temp;
}
if (n_bit > 0) {
temp = car;
car = car>>n_bit;
temp = temp<<(8-n_bit);
car = car|temp;
}
return car;
}
void arr_bit (short arr[], char c) {
short i = 7;
while (i >= 0) {
if (c != 0) {
arr[i--] = c&1;
c = c>>1;
}
else {
arr[i--] = 0;
}
}
}
In this case, the input variable is modified by the rotate_c function and the bit rappresentation of the character is 1111 1111
always.
Now if I change the variable n from short to int it is fully working!
And I just can't figure out why!!
Anyone can help me understanding why?
Sorry for the long post and see ya soon