[英]How to convert ASCII string to hexadecimal?
I have tried to find this topic on the web but I couldn't find the one I need. 我试图在网络上找到该主题,但找不到我需要的主题。
I have a string of character: 我有一串字符:
char * tempBuf = "qj"; char * tempBuf =“ qj”;
The result I want is 0x716A, and that value is going to be converted into decimal value. 我想要的结果是0x716A,并且该值将被转换为十进制值。
Is there any function in vc++ that can be used for that? vc ++中有没有可以用于此的函数?
You can use a stringstream to convert each character to a hexadecimal representation. 您可以使用字符串流将每个字符转换为十六进制表示形式。
#include <iostream>
#include <sstream>
#include <cstring>
int main()
{
const char* tempBuf = "qj";
std::stringstream ss;
const char* it = tempBuf;
const char* end = tempBuf + std::strlen(tempBuf);
for (; it != end; ++it)
ss << std::hex << unsigned(*it);
unsigned result;
ss >> result;
std::cout << "Hex value: " << std::hex << result << std::endl;
std::cout << "Decimal value: " << std::dec << result << std::endl;
}
So if I understood correctly the idea... 所以,如果我正确理解了这个主意...
#include <stdint.h>
uint32_t charToUInt32(const char* src) {
uint32_t ret = 0;
char* dst = (char*)&ret;
for(int i = 0; (i < 4) && (*src); ++i, ++src)
dst[i] = *src;
return ret;
}
If I understand what you want correctly: just loop over the characters, start to finish; 如果我正确理解了您想要的内容,请:循环遍历字符,然后从头开始; at each character, multiply the sum so far by 256, and add the value of the next character; 在每个字符处,将到目前为止的总和乘以256,然后加上下一个字符的值; that gives the decimal value in one shot. 一次给出十进制值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.