如何将char数组转换为字节数组? [英] How to convert a char array to a byte array?

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

问题描述

我正在处理我的项目,现在我遇到了一个问题,即如何将char数组转换为字节数组?

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]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 getNumonly 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
CD
EF
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位,因此它位于字节的高四位:0AA0.然后,将第二个值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.

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

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