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?
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:
strtol
strtoul
stdlib.h
cstdlib
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.
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; }
#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; }
std::string val ="00c4"; uint16_t out; if( (std::istringstream(val)>>std::hex>>out).fail() ) { /*error*/ }
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.
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; }
Source: https://habr.com/ru/post/1762127/More articles:Преобразование html в текст с использованием языка python - pythonrails how to know when send_file - ruby-on-railshttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1762124/google-app-engine-w-django-inboundmailhandler-appears-to-only-work-once&usg=ALkJrhgJwq7R1QYvp3Lmfcov-zTNIS4bPQReplace an element using phpquery (php version of jquery) - phpAbout autorun Qt Creator 2.0.0 - qtJQuery - live ('hover') and mousemove - jqueryREST WCF Authentication - securityhow to detect the presence of silence of a word / sound in a wav file using java? - javaGWT database for server-side data storage - javaДискриминационные союзы и наследование - inheritanceAll Articles