如何将字符串char转换为十六进制? [英] How do I convert string char to hex?

查看:250
本文介绍了如何将字符串char转换为十六进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在VC ++中使用MFC



我想每2个字符将字符串转换为十六进制数据格式。



char * stringA =0305CD6B;



char hexvalB [4]; // hexvalB是一个字节。



我想将stringA转换为hexvalB,意思是



'03' - > 0x03 - > hexvalB [0];

'05' - > 0x05 - > hexvalB [1];

'CD' - > 0xCD - > hexvalB [2];

'6B' - > 0x6B - > hexvalB [3];



我尝试过:



3小时浪费了什么功能使得从字符到1字节成为可能。

I am using MFC with VC++

I want to covert string to hex data format per 2 characters each.

char* stringA = "0305CD6B";

char hexvalB[4];// hexvalB is one byte.

I want to convert stringA to hexvalB, meaning

'03' -> 0x03 -> hexvalB[0];
'05' -> 0x05 -> hexvalB[1];
'CD' -> 0xCD -> hexvalB[2];
'6B' -> 0x6B -> hexvalB[3];

What I have tried:

3 hours wasted for what are the functions to make it possible from character to 1 byte.

推荐答案

你的评论错误:

Your comment is wrong:
char hexvalB[4];// hexvalB is one byte.

它不是一个字节,而是四个字节的数组。如果要在其中存储纯二进制数,则应将其声明为 unsigned char ,而不是 char

实际上,我使用数值代替数组,只使用标准函数:

It's not "one byte" it's an array of four bytes. And if you want to store pure binary numbers in it, you should declare it as unsigned char, not char.
In fact, I'd use a numeric value instead of an array, and just use standard functions:

unsigned long lValue = strtoul(stringA, NULL, 16);



如果你之后真的需要它作为数组,我会把它投出来:


If you really need it as an array after that, I'd cast it:

hexvalB = (unsigned char*) &lValue;



这有很好的理由,这与非单字节值的地址对齐有关,如果错误则可以得到问题。


There are good reasons for this, which have to do with the address alignment of values which aren't single byte and the problems you can get if they are wrong.


这篇关于如何将字符串char转换为十六进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆