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

前端 未结 5 940
被撕碎了的回忆
被撕碎了的回忆 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:26

    You can also use the function strtol(). If you use a base of 16 it will convert your hex string value to an int/long.

    errno = 0;
    my_int = strtol(my_str, NULL, 16);
    /* check errno */
    

    Edit: One other note, various static analysis tools may flag things like atoi() and scanf() as unsafe. atoi is obsolete due to the fact that it does not check for errors like strtol() does. scanf() on the other hand can do a buffer overflow of sorts since its not checking the type sent into scanf(). For instance you could give a pointer to a short to scanf where the read value is actually a long....and boom.

提交回复
热议问题