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

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

问题描述

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

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]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
光盘
英孚
98

AB
CD
EF
98

如何使用不同的长度输入.

循环不关心有多少数据,只要有偶数个输入(每个输出字节两个 ascii 字符)加上一个终止空值.它只是在遇到终止 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.

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

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