开发者

to create a header file to scan integer without using stdio.h(scanf)

I need to create a header file for function int read_int(), which scans an integer a开发者_Python百科nd returns it, without using scanf.

I have some knowledge on extended asm. I dont exactly know how to scan elements through the function asm__volatile .

down is the code i used for printing an integer (without using stdio.h).working perfectly

__asm__ __volatile__ (
    "movl $4, %%eax \n\t"
    "movl $1, %%ebx \n\t"
    "int $128 \n\t"
    :
    :"c"(buff), "d"(bytes)
) ; // $4: write, $1: on stdin


Which part is causing you trouble? Reading data from standard input is done using the read system call (see here for a list of syscalls on x86 linux) similar to the way you're using write to print:

int my_fgets(char* s, int size, int fd) {
    int nread;
    __asm__ __volatile__(
        "int $0x80\n\t"
    : "=a" (nread)
    : "a" (3), "b" (fd), "c" (s), "d" (size)
    );
    return nread;
}

Implementing your own getchar (should you so desire) using the above function is straight forward.

If it's the 'scanning' and reading of the integer that you're having trouble with, it can be done using the above function:

#define MY_STDIN 0
int read_int() {
    char buffer[256];
    int nr, number;

    nr = my_fgets(buffer, sizeof(buffer), MY_STDIN);
    if (nr < 1) {
        /* error */
    }
    buffer[nr - 1] = 0; // overwrite newline

    __asm__ __volatile__(
        "mov $0, %0\n\t" // initialize result to zero
        "1:\n\t" // inner loop
        "movzx (%%esi), %%eax\n\t" // load character
        "inc %%esi\n\t" // increment pointer
        "and %%eax, %%eax\n\t"
        "jz 2f\n\t" // if character is NUL, done
        "sub $'0', %%eax\n\t" // subtract '0' from character
        "add %%eax, %0\n\t" // add to result
        "jmp 1b\n\t" // loop
        "2:\n\t"
    : "=q" (number)
    : "S" (buffer)
    : "eax" // clobber eax
    );
    return number;
}

As this is for homework the above function is incomplete and will only work for the numbers 0 to 9, though extending it should be trivial.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜