ctype-conversionavr-gccuint8tteensy

How to display a uint8_t as an integer or string?


I am trialling a function that converts decimal numbers to binary, and I want to see if it is working or not. The problem is I am writing it in C for a Teensy micro controller, and I don't have many of the basic operations like printf. I am using a library that can only send information to the LCD screen as a string or double, so my only way to check if this function is working is to send the binary number to the LCD screen as a string or integer (if the binary number was 1010, the integer number would be 1010, not 10).

The libraries I am able to use are:

stdint
stdio
avr/io
avr/interrupt
util/delay
stdlib

Does anyone know how this can be done using the above libraries only?

EDIT: Included code as per comment request. The code I have used to convert the decimal to binary is:

uint8_t dec_to_bin(void){
    int n = 100;
    long long binaryNumber = 0;
    int remainder, i = 1;

    while (n!=0){
        remainder = n%2;
        n /= 2;
        binaryNumber += remainder*i;
        i *= 10;
    }
    return binaryNumber;
}

Then in the main function I have:

uint8_t a = dec_to_bin();
sprintf(a, "%u");

This returns the error: error: passing argument 1 of 'sprintf' makes pointer from integer without a cast


Solution

  • The definition for sprintf is

    int sprintf ( char * str, const char * format, ... );
    

    So if you want to convert your number into a string (and that is what sprintf does) you have to give it an array of char where to put the string:

    char output[9];
    uint32_t a = dec_to_bin(100);
    
    sprintf(output, "%08lu", a);
    

    That should solve your compile error.

    The second problem is you dec_to_bin function. The return values does not matches the value you are returning.

    uint32_t dec_to_bin( uint32_t n ){
    
        uint32_t binaryNumber = 0;
        uint32_t remainder, i = 1;
    
        //prevent overflow
        if ( n > 255) {
            return 0;
        }
    
        while (n!=0){
            remainder = n%2;
            n /= 2;
            binaryNumber += remainder*i;
            i *= 10;
        }
        return binaryNumber;
    }