#include <stdio.h>
#define NUMVALS 6
#define SIZE 5
#define MAX 31
int main () {
int vals = 0;
short curVal, idx = 0;
for(; idx < NUMVALS; ++idx) {
scanf("%d", &curVal);
vals = (vals << SIZE) | curVal;
}
printf("%d", vals | curVal);
return 0;
}
This is some code I am working on. It is supposed to store 6 integers each in the range from 0 to 31, so each gets a space of 5 bits. For some reason it is not working. When I make the assignment to vals in the loop, it seems to only be storing the current value read in into vals. Do you see what might be going wrong?
A halfway decent compiler will tell you:
warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘short int *’
scanf("%d", &curVal);
You need to use %hd
to scan a short
, or (in this case better) change your variable to int
.
If you're using GCC, add -Wall -Wextra -Werror
to your compilation command. It would have caught this for you.