如何将 char 数组转换为 byte 数组?
我正在处理我的项目,现在我遇到了一个问题,即如何将 char 数组转换为 byte 数组?.
I'm working on my project and now I'm stuck with a problem that is, how can I convert a char array to a byte array?.
例如:我需要将 char[9]
"fff2bdf1"
转换为字节数组,即 byte[4]
is <代码>0xff,0xf2,0xbd,0xf1.
For example: I need to convert char[9]
"fff2bdf1"
to a byte array that is byte[4]
is 0xff,0xf2,0xbd,0xf1
.
推荐答案
这里有一个小 Arduino 草图,说明了一种方法:
Here is a little Arduino sketch illustrating one way to do this:
void setup() {
Serial.begin(9600);
char arr[] = "abcdef98";
byte out[4];
auto getNum = [](char c){ return c > '9' ? c - 'a' + 10 : c - '0'; };
byte *ptr = out;
for(char *idx = arr ; *idx ; ++idx, ++ptr ){
*ptr = (getNum( *idx++ ) << 4) + getNum( *idx );
}
//Check converted byte values.
for( byte b : out )
Serial.println( b, HEX );
}
void loop() {
}
循环将继续转换,直到遇到空字符.getNum
中使用的代码也只处理小写值.如果您需要解析大写值,则可以轻松更改.如果您需要同时解析两者,那么它只需要多一点代码,如果需要,我会留给您(如果您无法解决并需要它,请告诉我).
The loop will keep converting until it hits a null character. Also the code used in getNum
only deals with lower case values. If you need to parse uppercase values its an easy change. If you need to parse both then its only a little more code, I'll leave that for you if needed (let me know if you cannot work it out and need it).
这会将转换后包含在out
中的4字节值输出到串行监视器.
This will output to the serial monitor the 4 byte values contained in out
after conversion.
AB
光盘
英孚
98
AB
CD
EF
98
如何使用不同长度的输入.
循环不关心有多少数据,只要有偶数个输入(每个输出字节有两个 ascii 字符)加上一个终止 null.它只是在遇到以 null 结尾的输入字符串时停止转换.
The loop does not care how much data there is, as long as there are an even number of inputs (two ascii chars for each byte of output) plus a single terminating null. It simply stops converting when it hits the input strings terminating null.
因此要在上面的草图中进行更长的转换,您只需要更改输出的长度(以适应更长的数字).即:
So to do a longer conversion in the sketch above, you only need to change the length of the output (to accommodate the longer number). I.e:
char arr[] = "abcdef9876543210";
byte out[8];
循环内的 4
不会改变.它正在将第一个数字移动到位.
The 4
inside the loop doesn't change. It is shifting the first number into position.
对于前两个输入 ("ab"
),代码首先将 'a' 转换为数字 10
或十六进制 A
.然后它向左移动 4 位,因此它位于字节的高四位:0A
到 A0
.然后将第二个值 B
简单地添加到给出 AB
的数字.
For the first two inputs ("ab"
) the code first converts the 'a' to the number 10
, or hexidecimal A
. It then shifts it left 4 bits, so it resides in the upper four bits of the byte: 0A
to A0
. Then the second value B
is simply added to the number giving AB
.
相关文章