How do I read hex numbers into an unsigned int in C

前端 未结 5 950
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 04:59

I\'m wanting to read hex numbers from a text file into an unsigned integer so that I can execute Machine instructions. It\'s just a simulation type thing that looks inside

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 05:09

    Do you want each of the lines (each 4 characters long) separated in 4 different array elements? If you do, I'd try this:

    /* read the line */
    /* fgets(buf, ...) */
    
    /* check it's correct, mind the '\n' */
    /* ... strlen ... isxdigit ... */
    
    /* put each separate input digit in a separate array member */
    num[i++] = convert_xdigit_to_int(buf[j++]);
    

    Where the function convert_xdigit_to_int() simply converts '0' (the character) to 0 (an int), '1' to 1, '2' to 2, ... '9' to 9, 'a' or 'A' to 10, ...

    Of course that pseudo-code is inside a loop that executes until the file runs out or the array gets filled. Maybe putting the fgets() as the condition for a while(...)

    while(/*there is space in the array && */ fgets(...)) {
    }
    

提交回复
热议问题