SOLVED - Splitting char array apart and storing as array of bytes.

That's probably a terrible subject title, but I can't think how else describe it. Sorry.

I'm receiving data from a WT32i Bluetooth module, and I'm struggling to figure out how to parse a particular piece of data.

Given the following as an example:

char features[] = "0000000000b7011c0200000000000000";

I need to get it into the following format:

byte features[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0xB7, 0x01, 0x1C, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

When viewed in binary, each bit of each byte represents the available features of a media player, so it's important to retain all the zeros. I've been staring at it for ages now, but can't think how to tackle this one. I'm not looking for people to write code for me, but even a nudge in the right direction would be appreciated.

If you're curious, the breakdown of features/bits is listed on page 75 of this document:

https://www.bluetooth.org/docman/handlers/DownloadDoc.ashx?doc_id=119996

Ian.

char chars[] = "hello";
byte * bytes;

bytes = ( byte*)( void*) &chars;

Bytes now points to chars using the same memory

Here is how I would do it: dRhpnh - Online C++ Compiler & Debugging Tool - Ideone.com

(edit: fixed bug ^^)

@guix: Nice!

To convert an ASCII hexadecimal digit into a 4-bit binary number:

byte char2nybble(char ch) {
  if(ch <= '9') return ch - '0';
  else if(ch <= 'F') return ch - 'A' + 10;
  else return ch - 'a' + 10;
}

To assemble two nybbles into a byte (assuming that both nybbles are 'clean' - 0 to 16):

byte assemble(byte hi, byte lo) {
  return (hi << 4) | lo;
}

You can combine the expressions and do this in one line if you want. Or you can inline the functions or make a macro.

Many thanks for your assistance with this.

I went with Guix's solution in the end. I had to read through it a few times to see how it works (only recently started to understand pointers), but I have one question.

Regarding - while ( *p ).

Does that cease to be true when the pointer is pointing to the Null terminator at the end of the char array ?

@Paul,

I've recently been reading through your Object Oriented way of doing things. I really like the concept of everything having its own setup & loop methods. I hope to try and implement this into my current project.

Ian.

ian332isport:
Regarding - while ( *p ).

Does that cease to be true when the pointer is pointing to the Null terminator at the end of the char array ?

Yes.

Excellent. I guess you can teach an old dog new tricks :slight_smile:

Ian.