简体   繁体   中英

Binary to dec and hex in C

I would like to create function that will return numbers in hexidecimal. But I am getting some wrong numbers after changing to decimal numbers. In output, the first number is binary, second one also binary but in int format, and third one should be decimal. But I am getting wrong numbers in decimal (see the second line, where it shoud be 156, not 220). Could anyone explain me what am i doing wrong and how can I get right numbers? Thank you. Here is my output:

在此处输入图片说明

    char *encrypted = calloc((size_t)TEXT_LEN*3, sizeof(char));
int number[TEXT_LEN];
index=0;
for(int i=0;i<TEXT_LEN;i++){

    number[i]=atoi(binary[i]);

    printf("%s ",binary[i]);
    printf("%d ",number[i]);
    printf("%d\n",(unsigned char)number[i]);

    sprintf(encrypted+index,"%x ",(unsigned char)number[i]);

    index+=3;
}

printf("%s\n",encrypted);
free(encrypted);

EDIT: I found solution in comments, and I fixed it by using function strtol in line:

number[i] = strtol ( binary[i], NULL, 2);

In case of number values smaller than 16 the written string length is two and at the end the char '\\0' is inserted. Use either a fixed size

sprintf(encrypted+index,"%02x ", number[i]);
index += 3;

or use the return value from the sprintf function which is the written string length to increment the index

index += sprintf(encrypted+index,"%x ", number[i]);

I would prefer a combination of both

index += sprintf(encrypted+index,"%02x ", number[i]);

Based on the eight character string in binary the method of user3121023 above will give you the right decimal number

number[i] = strtol(binary[i], NULL, 2);
printf("%s ", binary[i]); // 1st col
printf("%d\n", number[i]); // 2nd col

In the second line of output, I wrote a C plus plus program to explain your doubt:

int value = 10011100;
cout<<bitset<sizeof(int)*8>(value)<<value<<endl;    // 0000000010011000110000011101110010011100
unsigned char va = (unsigned char)value;
cout<<bitset<sizeof(unsigned char)*8>(va)<<endl;    // 11011100

the decimal number 10011100 convert to binary number 10011000110000011101110010011100 , then it is put in unsigned char, we get 11011100 , it is 220.

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