简体   繁体   English

C ++ Char数组转换为Hex或char数组

[英]C++ Char array conversion to Hex or char array

I would appreciate for some C++ expertize advice on this please. 对于此方面的一些C ++专业知识建议,我将不胜感激。 I have a Char array 我有一个字符数组

     <unsigned char ch1[100];> 

data (ASCII code) gets filled in this ( max 6 or 8 array spaces and rest is empty). 数据(ASCII代码)将被填充到其中(最多6或8个数组空间,其余为空)。 I want to process valid bits in the array only either converting them to Hex or again Char array. 我只想将数组中的有效位转换为十六进制或再次将其转换为Char数组。 I tried 我试过了

     <memcpy (ch1,ch2,sizeof(ch1))>

but all garbage values are also copied..... :( 但是所有垃圾值也会被复制..... :(

       <strcpy gives me an error>

also number of bytes copied are dynamic ( 1 time :- 4; 2 time :- 6.....) 复制的字节数也是动态的(1次:-4; 2次:-6 .....)

So only copy the chars that are actually initialized. 因此,仅复制实际初始化的字符。 You as a programmer are responsible for tracking what's initialized and what's not. 作为程序员, 负责跟踪初始化的内容和未初始化的内容。

Do you know how many valid bytes do you have in your array? 您知道数组中有多少个有效字节吗? If yes, you can pass that number in as the 3rd argument of memcpy. 如果是,则可以将该数字作为memcpy的第三个参数传递。

Otherwise you can zero-initialize the array and use strcpy which will stop on the first zero: 否则,您可以对数组进行零初始化并使用strcpy,它将在第一个零处停止:

char ch1[100];
// zero out the array so we'll know where to stop copying
memset(ch1, 0, sizeof(ch1));

... data gets filled here ....

strcpy (ch2, ch1);
// zero out array again so we'll catch the next characters that come in
memset(ch1, 0, sizeof(ch1));

... life goes on ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM