# Convert string to bytes array

**URL:** <https://forum.arduino.cc/t/convert-string-to-bytes-array/320962>\
**Category:** Programming\
**Created:** [June 29, 2015, 12:32pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962 "2015-06-29T12:32:01Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![MMJZ](https://avatars.discourse-cdn.com/v4/letter/m/439d5e/32.png) [@MMJZ](https://forum.arduino.cc/u/MMJZ)\
**Post date:** [June 29, 2015, 12:32pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/1 "2015-06-29T12:32:01Z")

</div>

HI,

I receive a string by serial as: "13ABF2C1"  
and I want to convert it to bytes as: byte b[4] = {13, AB, F2, C1}  
so that when i rewrite:

```cpp
for(int i=0; i<4; i++)
{
     serial.print(b[i], HEX);
     serial.print(", ");
}

```

the output should be: 13, AB, F2, C1,

How I can do this conversion?!  
any help appreciated

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [June 29, 2015, 12:32pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/2 "2015-06-29T12:32:35Z")

</div>

sscanf?

(BTW, did you remember typing your post in _italics_?  
No, you don't.  
Please use code tags when posting code.)

---

<div class="post-metadata">

**Author:** ![econjack](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/econjack/32/1105255_2.png) [@econjack](https://forum.arduino.cc/u/econjack)\
**Post date:** [June 29, 2015, 12:44pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/3 "2015-06-29T12:44:00Z")

</div>

I think using scanf() is often an H-bomb-to-kill-an-ant. It can do a lot of things, but programs often use only a small fraction of its utility, resulting in a program that's bigger than it might be. Try these edits to your code:

```cpp
byte b[4] = {0x13, 0xAB, 0xF2, 0xC1};    // Make it clear they are hex numbers

void setup() {
  Serial.begin(9600);
  for (int i = 0; i < 4; i++)
  {
    Serial.print(b[i], HEX);            // You need to subscript the array
    Serial.print(", ");
  }
}
void loop() {
}

```

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [June 29, 2015, 12:49pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/4 "2015-06-29T12:49:13Z")

</div>

> // You need to subscript the array

It was subscripted, but the forum mangled the `[i]` into an italics tag.

Agreed, sscanf is overkill, but if it gets you further down the road quicker, why not?  
Knowing that it's bloated, you can optimise later if necessary.

```arduino
 sscanf (string, "%2x%2x%2x%2x", &b [0], &b [1], &b [2], &b [3]);

```

---

<div class="post-metadata">

**Author:** ![septillion](https://avatars.discourse-cdn.com/v4/letter/s/c5a1d2/32.png) [@septillion](https://forum.arduino.cc/u/septillion)\
**Post date:** [June 29, 2015, 1:04pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/5 "2015-06-29T13:04:30Z")

</div>

Is everybody missing the fact he's receiving a string and all he want's to do is insert ", "...

```cpp
  for(byte i = 0; myString[i]; i++){
    if(i % 2 == 0 && i != 0){
      Serial.print(", ");
    }
    Serial.print(myString[i]);
  }

```

With myString the received string.

---

<div class="post-metadata">

**Author:** ![econjack](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/econjack/32/1105255_2.png) [@econjack](https://forum.arduino.cc/u/econjack)\
**Post date:** [June 29, 2015, 1:05pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/6 "2015-06-29T13:05:06Z")

</div>

> Agreed, sscanf is overkill, but if it gets you further down the road quicker, why not?  
> Knowing that it's bloated, you can optimise later if necessary.

Not sure I agree with you this time. The "why not?" answer is: Teaching shortcuts at the outset usually perpetuates bad coding habits down the road. Besides, I really don't see how it gets you down the road faster. Once you see the mistakes (I did forget about the mangling that the italics did), I thinks it's faster to write it without _sscanf()_. As to the code size, my version takes 1990 bytes while the _sscanf()_ version takes 3880; almost twice as big. To me, this small rewrite isn't an optimization, it just takes advantage of what's already in place (e.g., defining things correctly and using the Serial object) plus it avoids defining a _char_ array that really isn't needed.

The good news is that the OP can choose for himself. We each demonstrated a tool that he can now hang on his belt...more tools is good. After all, if the only tool you have is a hammer, it's not too surprising that all problems look like a nail.

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [June 29, 2015, 1:06pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/7 "2015-06-29T13:06:16Z")

</div>

> Is everybody missing the fact

I don't think it's a fact until the OP says it's a fact.

---

<div class="post-metadata">

**Author:** ![septillion](https://avatars.discourse-cdn.com/v4/letter/s/c5a1d2/32.png) [@septillion](https://forum.arduino.cc/u/septillion)\
**Post date:** [June 29, 2015, 1:08pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/8 "2015-06-29T13:08:54Z")

</div>

econjack, I think you both miss the point of the TS. The printing isn't the problem but "converting" it to the array of bytes. Because he receives a string.

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [June 29, 2015, 1:11pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/9 "2015-06-29T13:11:32Z")

</div>

> The printing isn't the problem but "converting" it to the array of bytes.

Which is why I presented a means of converting the string into an array, in reply #3.

---

<div class="post-metadata">

**Author:** ![septillion](https://avatars.discourse-cdn.com/v4/letter/s/c5a1d2/32.png) [@septillion](https://forum.arduino.cc/u/septillion)\
**Post date:** [June 29, 2015, 1:16pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/10 "2015-06-29T13:16:20Z")

</div>

Your right. But I think that's indeed using a nuclear bomb to kill an ant...

---

<div class="post-metadata">

**Author:** ![MMJZ](https://avatars.discourse-cdn.com/v4/letter/m/439d5e/32.png) [@MMJZ](https://forum.arduino.cc/u/MMJZ)\
**Post date:** [June 29, 2015, 1:19pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/11 "2015-06-29T13:19:01Z")

</div>

Mr. econjack, (0x13) it works when i enter constant value, but in my case the value is received serialy.  
Mr. AWOL, the received string contain extra info also (received string form: Cmd\_DEL\_13ABF2C1), so is the sscanf still work?!  
Mr. septillion, no the printing is not my goal, my goal is the conversion itself because also I need to do a compare it with another bytes array, in addition Mr. septillion, what this (ant) do to kill him with nuclear bomb?!!!

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [June 29, 2015, 1:20pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/12 "2015-06-29T13:20:39Z")

</div>

It's a bomb OK, the format specifier should be "%2cx".  
Sorry.

Look, guys, I know it's sledgehammer, and if I were chasing the bytes, I'd've coded it as nibble-by-nibble explicit conversion, but I'm trying to get the guy moving.

Yes, sscanf will still work, it just needs a little more work.

---

<div class="post-metadata">

**Author:** ![guix](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/guix/32/215371_2.png) [@guix](https://forum.arduino.cc/u/guix)\
**Post date:** [June 29, 2015, 1:25pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/13 "2015-06-29T13:25:19Z")

</div>

strtoul, or sscanf as suggested already.

```cpp
char s[] = "13ABF2C1";
uint8_t b[4];
uint32_t n = strtoul( s, NULL, 16 );

b[0] = ( n >> 24 ) & 0xFF;
b[1] = ( n >> 16 ) & 0xFF;
b[2] = ( n >>  8 ) & 0xFF;
b[3] = ( n & 0xFF );

```

---

<div class="post-metadata">

**Author:** ![septillion](https://avatars.discourse-cdn.com/v4/letter/s/c5a1d2/32.png) [@septillion](https://forum.arduino.cc/u/septillion)\
**Post date:** [June 29, 2015, 1:39pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/14 "2015-06-29T13:39:06Z")

</div>

is the structure of the string always the same? aka, 16 chars? And do you really need to break it up into 3 pieces?

you can do something like:

```cpp
out = strtol(&myString[8], &pEnd, 16);

```

Stores it into a long.

---

<div class="post-metadata">

**Author:** ![guix](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/guix/32/215371_2.png) [@guix](https://forum.arduino.cc/u/guix)\
**Post date:** [June 29, 2015, 1:47pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/15 "2015-06-29T13:47:08Z")

</div>

If you don't care about the bytes being in the "wrong" order:

```cpp
char s[] = "13ABF2C1";
uint8_t b[4];
*( uint32_t * )b = strtoul( s, NULL, 16 );

```

---

<div class="post-metadata">

**Author:** ![econjack](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/econjack/32/1105255_2.png) [@econjack](https://forum.arduino.cc/u/econjack)\
**Post date:** [June 29, 2015, 2:07pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/16 "2015-06-29T14:07:12Z")

</div>

Or:

```cpp
byte b[4];
char msg[] = "13ABF2C1";

void setup() {
  int i;
  int j;
  char temp[3];
  
  Serial.begin(9600);

  j = 0;
  for (int i = 0; i < 8; i += 2)
  {
    strncpy(temp, &msg[i], 2);
    // Convert 2-character hex string to numeric:
    b[j] = (temp[0] <= '9') ? (temp[0] - '0') : (temp[0] - 'A' + 10);
    b[j] *= 16;
    b[j] += (temp[1] <= '9') ? (temp[1] - '0') : (temp[1] - 'A' +10);

    Serial.print(b[j++], HEX);
    Serial.print(", ");
  }
}
void loop() {
}

```

which bumps the code size to 2116 vs 3880 for _sscanf()_;

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [June 29, 2015, 2:14pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/17 "2015-06-29T14:14:54Z")

</div>

> which bumps the code size to 2116 vs 3880 for sscanf();

...but fails if you pass it the perfectly legal "13abf2c1" 😉

---

<div class="post-metadata">

**Author:** ![econjack](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/econjack/32/1105255_2.png) [@econjack](https://forum.arduino.cc/u/econjack)\
**Post date:** [June 29, 2015, 2:23pm UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/18 "2015-06-29T14:23:44Z")

</div>

@AWOL: Opps! change to:

```cpp
byte b[4];
//char msg[] = "13ABF2C1";
char msg[] = "13abf2c1";

void setup() {
  int i;
  int j;
  char temp[3];
  
  Serial.begin(9600);

  j = 0;
  for (int i = 0; i < 8; i += 2)
  {
    msg[i] = toupper(msg[i]);              // To handle upper and lower case...
    strncpy(temp, &msg[i], 2);

    // Convert hex string to numeric:
    b[j] = (temp[0] <= '9') ? (temp[0] - '0') : (temp[0] - 'A' + 10);
    b[j] *= 16;
    b[j] += (temp[1] <= '9') ? (temp[1] - '0') : (temp[1] - 'A' +10);

    Serial.print(b[j++], HEX);
    Serial.print(", ");
  }
}
void loop() {
}

```

---

<div class="post-metadata">

**Author:** ![MMJZ](https://avatars.discourse-cdn.com/v4/letter/m/439d5e/32.png) [@MMJZ](https://forum.arduino.cc/u/MMJZ)\
**Post date:** [June 30, 2015, 8:26am UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/19 "2015-06-30T08:26:48Z")

</div>

Mr. guix I try your suggestion code in reply #12  
it convert the string:"13ABF2C1" to: 00 AB F2 C1  
as you see there is a bug in the beginning, why this bug?!  
also I see this way is complex, is there simplest way?!

sorry the buy was in my test code!!!  
I optimize the function to be as in the reply #20

---

<div class="post-metadata">

**Author:** ![MMJZ](https://avatars.discourse-cdn.com/v4/letter/m/439d5e/32.png) [@MMJZ](https://forum.arduino.cc/u/MMJZ)\
**Post date:** [June 30, 2015, 9:17am UTC](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962/20 "2015-06-30T09:17:01Z")

</div>

Mr. econjack, I try your suggestion code in reply #17  
the output is: 13, CB, F2, C1,  
while the msg was: "13abf2c1"  
the 3rd digit is 'a' and convert to 'C'?!!!  
Note that, when change the input string to upper case the output became true

[Next page](https://forum.arduino.cc/t/convert-string-to-bytes-array/320962.md?page=2)
