Converting a string with a hexadecimal representation of a number to an actual numeric value

前端 未结 6 915
渐次进展
渐次进展 2020-12-21 10:49

I have a string like this:

\"00c4\"

And I need to convert it to the numeric value that would be expressed by the literal:

0         


        
相关标签:
6条回答
  • 2020-12-21 10:55

    The strtol function (or strtoul for unsigned long), from stdlib.h in C or cstdlib in C++, allows you to convert a string to a long in a specific base, so something like this should do:

    char *s = "00c4";
    char *e;
    long int i = strtol (s, &e, 16);
    // Check that *e == '\0' assuming your string should ONLY
    //    contain hex digits.
    // Also check errno == 0.
    // You can also just use NULL instead of &e if you're sure of the input.
    
    0 讨论(0)
  • 2020-12-21 10:57
    std::string val ="00c4";
    uint16_t out;
    if( (std::istringstream(val)>>std::hex>>out).fail() )
    { /*error*/ }
    
    0 讨论(0)
  • 2020-12-21 11:00

    There is no such thing as an 'actual hex value'. Once you get into the native datatypes you are in binary. Getting there from a hex string is covered above. Showing it as output in hex, ditto. But it isn't an 'actual hex value'. It's just binary.

    0 讨论(0)
  • 2020-12-21 11:01
    #include <stdio.h>
    
    int main()
    {
            const char *str = "0x00c4";
            int i = 0;
            sscanf(str, "%x", &i);
            printf("%d = 0x%x\n", i, i);
            return 0;
    }
    
    0 讨论(0)
  • 2020-12-21 11:10

    You can adapt the stringify sample found on the C++ FAQ:

    #include <iostream>
    #include <sstream>
    #include <stdexcept>
    
    class bad_conversion : public std::runtime_error
    {
    public:
      bad_conversion(std::string const& s)
        : std::runtime_error(s)
      { }
    };
    
    template<typename T>
    inline void convert_from_hex_string(std::string const& s, T& x,
      bool failIfLeftoverChars = true)
    {
      std::istringstream i(s);
      char c;
      if (!(i >> std::hex >> x) || (failIfLeftoverChars && i.get(c)))
        throw ::bad_conversion(s);
    }
    
    int main(int argc, char* argv[])
    {
      std::string blah = "00c4";
      int input;
      ::convert_from_hex_string(blah, input);
      std::cout << std::hex << input << "\n";
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-21 11:17
    int val_from_hex(char *hex_string) {
        char *c = hex_string;
        int val = 0;
        while(*c) {
            val <<= 4;
            if(*c >= '0' && *c <= '9')
                val += *c - '0';
            else if(*c >= 'a' && *c <= 'f')
                val += *c - 'a' + 10;
            c++;
        }
        return val;
    }
    
    0 讨论(0)
提交回复
热议问题