简体   繁体   中英

How to convert a char array to a byte array?

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?.

For example: I need to convert char[9] "fff2bdf1" to a byte array that is byte[4] is 0xff,0xf2,0xbd,0xf1 .

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() {
}

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).

This will output to the serial monitor the 4 byte values contained in out after conversion.

AB
CD
EF
98

Edit: How to use different length inputs.

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). Ie:

char arr[] = "abcdef9876543210";
byte out[8];

The 4 inside the loop doesn't change. It is shifting the first number into position.

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 .

Just shift 0 or 1 to its position in binary format :)

char lineChars[8] = {1,1,0,0,0,1,0,1}; 
    char lineChar = 0;
    for(int i=0; i<8;i++)
    {
        lineChar |= lineChars[i] << (7-i);
    }

Example 2. But is not tested!

void abs()
{
  char* charData = new char;
  *charData = 'h';
  BYTE* byteData = new BYTE;
  *byteData = *(BYTE*)charData; 
}

Assuming you want to parse the hex values in your string, and two letters always make up one byte value (so you use leading zeros), you can use sscanf like this:

char input[] = "fff2bdf1"; 
unsigned char output[4];
for (int i=0; i<4; i++) {
  sscanf(&input[i*2], "%02xd", &data[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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