Clash
Clash

Reputation: 5025

Using write syscall to print integers

I would like to have the equivalent of

void print3( char a, uint8_t b, int8_t c )
{
    printf("%c %" PRIu8 " %" PRIi8 "\n", a, b, c);
}

using the write syscall. The problem is, I don't know how to print an integer using write. Only commands from ANSI C are allowed and using sprintf to format strings is forbidden.

Example syntax to use write:

const char msg[] = "Hello World!";
write(STDOUT_FILENO, msg, sizeof(msg)-1);

Edit: I am not allowed to use sprintf neither itoa.

Upvotes: 0

Views: 5133

Answers (4)

iabdalkader
iabdalkader

Reputation: 17312

Consider the number 155, if you divide by 100 then there's 1 hundred and the remainder is 55, divide by 10 you get 5 10s and the remainder is 5, divide that by 1 you get 5. now concatenate those numbers 1-5-5 you get the final number.This should get you started.

Upvotes: 2

0x90
0x90

Reputation: 40982

Do you know that 9(in ascii) == '0' + 9 :

char a =0;
a = '0';
printf("%c",a); //will print 0
a = '0' + 8; 
printf("%c",a);//will print 8

enter image description here

EDIT:

int a = 1234;

now to convert it to char* b: algorithm:

for each digit in a:
   b.append(digit+'0')

you have to understand that char is a container of 8 bits == byte and can be a number, a letter in ASCII or whatever you want to represent within 8 bits

Upvotes: 1

LSerni
LSerni

Reputation: 57388

You will have to do the conversion yourself. The code below converts to ASCIIZ (C string), not simple ASCII, but it's useable:

int ltoa(long x, char *str, size_t str_size)
{
    long y = 1;
    size_t i, s;
    for (s = 0; y < x; s++)
        y *= 10;
    if (str_size < s+1)
        return s+1;
    str[s--] = 0x0;
    while(s)
    {
            str[s--] = '0' + (x % 10);
            x /= 10;
    }
    str[0] = '0' + x;
    return 0;
}

Upvotes: 1

Doug Currie
Doug Currie

Reputation: 41180

Each digit of the number to be printed is represented as a character.

There are two pieces to the solution:

  • calculate the digits of the number in the chosen base, 10 I assume in this case

  • convert the digit to a character and write it

For the step of calculating the digits, you will use the / and % operators; this will give the digits in "reverse" order, so you'll need to squirrel them away before writing them.

For converting the digits to characters, consider two approaches: simple arithmetic (using the ASCII character values), or an array lookup.

Upvotes: 1

Related Questions