简体   繁体   中英

Program to convert octal to binary number system

i am a beginner in c programing language and in this few days i'm train to do some c exercises and i get stucked in some exercice for conversions: so this is what i had did

#include <stdio.h>

#include <string.h>

int main() {

    int num[8] = {
        0,
        1,
        2,
        3,
        4,
        5,
        6,
        7
    };
    long long binary, octal, tempoctal;
    int last, i, A, tempi;
    char hex[9] = {
        '000',
        '001',
        '010',
        '011',
        '100',
        '101',
        '110',
        '111'
    };
    int bex[10];
    A = 0;

    printf("enter an octal number:  ");
    scanf("%lld", & octal);

    tempoctal = octal;

    while (tempoctal != 0) {
        last = tempoctal % 10;

        for (i = 0; i < 8; i++) {
            if (num[i] == last) {
                tempi = i;
                bex[A] = tempi;

            }
        }

        A++;
        tempoctal /= 10;
    }

    printf("\nthe is %s", bex);

    return 0;
}

so i want just to know why when i want to print the array of bex i get error on the consol enter image description here . Although i know the solution but i want to do it in my own way.

Answering your question. bex is declared as int bex[10] , array of integers. printf("%s"... expects a character string, not an array of int.

  • A character string is usually an array of chars char bex[10] . Char is a single byte, and an int is usually 4-byte long. So, you see the difference there. In your example you modify the lowest byte of the 'int', leaving other 3 as '0'.

  • printable chars have corresponding codes. For example a char of '0' has code of 48 in asccii encoding. All other chars that represent numbers have consecutive codes (48..57). This how the printf and other services know what to print if they see 48 in the byte.

  • the string in 'c' ends with a stray 0 , so that the printf knows where to stop reading the chars.

So, if you want to print 'bex' as a string, you need to create it as a string. for example

char bex[10];

 for (i=0; i <8; i++)
     bex[A++] = '0' + i; // code of '0' + a number
 bex[A] = 0; // string terminator

Just make sure that your 'A' is always less than '8' to avoid array overflow (string length of 9 plus one character for the terminator. Now you can do this.

 printf("%s", bex);

You have to work on the rest of the program, because it does not do anything useful in the current state, but this should help you to get going.

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