All submissions

Convert Decimal Number to Binary or Hex Without itoa function

Code

#include <stdio.h>
#include <stdint.h>
#include <string.h>

typedef union {
    uint16_t num;
    uint8_t bytes[2];
}DTH_T;

void print_base(uint16_t num, uint8_t base) {
    
    
    char result_buffer[16];
    int buffer_index = 0;
    memset(result_buffer,'\0',sizeof( result_buffer));

    if(base==2)
    {
        if (num!=0)
        {
            uint8_t reminder = 0;

            while(num!=0)
            {
                reminder = (num%2);
                num = num/2;
                result_buffer[buffer_index] = (reminder)+(48);
                buffer_index++;
            }
        }

        else
        {
            result_buffer[buffer_index++] = '0';
        }


        result_buffer[buffer_index] = '\0';

        for (int i=buffer_index-1; i>=0; i--)
        {
            printf("%c",result_buffer[i]);
        }
    }

    else
    {
        DTH_T T;
        T.num = num;

        if (num<=255)
        {
            printf("%X",T.bytes[0]);
        }

        else
        {
            printf("%X%X",T.bytes[0],T.bytes[1]);
        }

    }
}

int main() {
    uint16_t num;
    uint8_t base;
    scanf("%hu %hhu", &num, &base);

    print_base(num, base);
    return 0;
}

Solving Approach

 

 

 

Loading...

Input

10 2

Expected Output

1010