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

I have a line like this:

"00c4"

And I need to convert it to a numerical value that would be expressed by a literal:

0x00c4

How should I do it?

+3
source share
6 answers

A function strtol(or strtoulfor an unsigned long), from stdlib.hin C cstdlibto C ++, allows you to convert a string to a long one in a specific database, 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.
+3
source

You can adapt the stringify example found in the C ++ Frequently Asked Questions :

#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;
}
+2
source
#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;
}
+2
std::string val ="00c4";
uint16_t out;
if( (std::istringstream(val)>>std::hex>>out).fail() )
{ /*error*/ }
+1

There is no such thing as an “actual hexadecimal value”. Once you get into native data types, you are in binary format. How to get there from a hexadecimal string. Showing it as a result in hexadecimal format is the same. But this is not an "actual hexadecimal value". It is just binary.

+1
source
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
source

Source: https://habr.com/ru/post/1762127/


All Articles