I am working on the print_selected(int x) function which, takes x then extracts bits 5, 6, 7, and 8 (starting from bit 0 at the rightmost) then print them in both binaries then in hexadecimal.
There is a helper function, int2bin(int n) within the print_selected(int x) and int2bin(int) function returns a char type array to s.
The problem is that I can print out the binary number of bits of 5, 6, 7, and 8bits correctly, however, the hexadecimal number returns somehow weird number(due to the memory leaking issue?). I strongly doubt that char* s = int2bin(x) and free(s) within print_selected(int) might be the problem but I do not know which part I should make a change to correctly print out the right hexadecimal number.
#include <stdlib.h> #include <stdio.h> #include <math.h> // takes integer and returns char array with 32 binary number. char* int2bin(int n) { int nbits = sizeof(n) * 8; char *s = malloc(nbits + 1); s[nbits] = '\0'; unsigned int u = *(unsigned int*)&n; int i; unsigned int mask = 1 << (nbits - 1); for (i = 0; i < nbits; i++, mask >>= 1) s[i] = ((u & mask) != 0) + '0'; return s; } // takes an integer and print in "binary" and "hexadecimal". void print_selected(int x) { int hex[4]; // to store the 4 bits of (5,6,7,8) int i; char *s = int2bin(x); // I think this part makes problem? printf("bits 5 to 8 in bin: "); for (i = 23; i <= 26; i++) { printf("%d", s[i] - '0'); hex[i] = s[i] - '0'; } free(s); // I think this part makes problem? printf("\n"); int j = 3; // since we already know the number of bits, int sum = 0; for (i = 0; i <= 3; i++) { sum = sum + (hex[i] * pow(2, j)); j--; } printf("in hex: 0x%x\n", sum); } int main(void) { int a = 278; print_selected(a); }
free(s). You don't use that memory any more.pow(2, j). You don't need maths for this, just(1 << j).