简体   繁体   中英

My C function isn't returning the right int-to-binary value

I'm trying to create a function that returns the binary equivalent of a given integer. But when given the test input of 1234, it returns the incorrect value of both the given input's binary and the left-shifted version's binary:

Enter a base-10 integer: 1234
Enter number of places to shift bit: 8

1234 1421075418
315904 1826920960

The given value and left-shifted value are correct, but the binary equivalents aren't.

int showbits(int value) {
  return (value == 0 || value == 1 ? value : ((value % 2) + 10 * showbits(value / 2)));
}

void left_bit_shift() {
  int value = get_single_base_10();
  int number_shift = get_number_shift();
  int bit_value = showbits(value);

  int left_shifted_value = value << number_shift;
  int left_shifted_bit = showbits(left_shifted_value);

  printf("%d %d\n", value, bit_value);
  printf("%d %d", left_shifted_value, left_shifted_bit);
}

int get_single_base_10() {
  int value;
  printf("Enter a base-10 integer: ");
  scanf("%d", &value);
  return value;
}

int get_number_shift() {
  int shift;
  printf("Enter number of places to shift bit: ");
  scanf("%d", &shift);
  return shift;
}

Because binary of 1234 is 10011010010 which can not be stored in an integer variable on your machine. If you change return type of showbits() to long, it might work. But this is not a permanent solution to get binary value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM