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);
}
The problem is here:
for (i = 23; i <= 26; i++)
{
printf("%d", s[i] - '0');
hex[i] = s[i] - '0';
}
hex
indexes go from 0
to 3
, so assigning to hex[23]
causes undefined behavior. Then you try to print the elements of hex
, which you never actually filled in.
You need:
hex[i - 23] = s[i] - '0';
however, the hexadecimal number returns somehow weird number(due to the memory leaking issue?).
no, you access to non initialized memory in
for (i = 0; i <= 3; i++) { sum = sum + (hex[i] * pow(2, j)); j--; }
because hex is only initialized in
for (i = 23; i <= 26; i++) { printf("%d", s[i] - '0'); hex[i] = s[i] - '0'; }
so for the indexes 23 to 26, not for the indexes 0 to 3
note you also write out of hex , with an undefined bahevior, you need to use the index i -23
to write hex
so the value of sum is undefined
I encourage you to use valgrind to detect your memory problems, I used it to answer you
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.