[英]How to Convert hexadecimal integer into a string in c++ (for html colors)?
[英]how to convert a hexadecimal string to a corresponding integer in c++?
我有一個存儲在文件中的unicode映射。
像下面這一行用制表符分隔。
a 0B85 0 0B85
第二列是unicode字符。 我想將其轉換為0x0B85,它將存儲在int變量中。
怎么做?
您可以使用strtol
,它可以將數字解析為long,然后您可以將其分配給int
。 strtol
可以使用2到36的任何基數來解析數字(即任何可以用字母數字字符表示的基數)。
例如:
#include <cstdlib>
using namespace std;
char *token;
...
// assign data from your file to token
...
char *err; // points to location of error, or final '\0' if no error.
int x = strtol(token, &err, 16); // convert hex string to int
您已經要求使用C ++,所以這里是使用流的規范C ++解決方案:
#include <iostream>
int main()
{
int p;
std::cin >> std::hex >> p;
std::cout << "Got " << p << std::endl;
return 0;
}
如果在您的情況下需要,可以用std::cin
替換字符串流。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.