# Convert String to byte - getting 'invalid cast; error

**URL:** <https://forum.arduino.cc/t/convert-string-to-byte-getting-invalid-cast-error/1293536>\
**Category:** Programming\
**Created:** [August 20, 2024, 3:33am UTC](https://forum.arduino.cc/t/convert-string-to-byte-getting-invalid-cast-error/1293536 "2024-08-20T03:33:57Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![brandonstone](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/brandonstone/32/977807_2.png) [@brandonstone](https://forum.arduino.cc/u/brandonstone)\
**Post date:** [August 20, 2024, 3:33am UTC](https://forum.arduino.cc/t/convert-string-to-byte-getting-invalid-cast-error/1293536/1 "2024-08-20T03:33:57Z")

</div>

I need help. I am trying to convert a String of numbers into individual bytes, but I am getting an "Invalid cast from type 'arduino::String' to type 'byte {aka unsigned char}" error message. The Arduino doccumentation for type conversion says I can use byte() to convert any value type to byte, so I don't understand why it is "invalid".

I understand that using Strings can lead to a whole host of issues. The main reason I am using them is because the code I copied and adapted used them. So, if there is a way I can avoid using them, feel free to suggest. But, I warn you, I am a complete novice (approx 3 weeks of experience), and every mention of char\* arrays has left me more confused than before. So, dumb it down for me.

To (attempt to) explain the purpose of the code: this code is for what I am calling motorUnit. I will have another Arduino (controlUnit) that is acting as WiFi Access Point and Server Host. This controlUnit will send both commandWord and variableRequest messages. The syntax of the messages is either commandWord:xxxxxxxxxxx (where each x is a 0 or 1), or \<motorUnit\_x:"variable"?\> The return message syntax will be \<motorUnit\_x:"variable":"value"\> (where x is the board number, in this case 0, "variable" will be the specific variable that is being requested, such as shutterStatus, batteryLevel, signalStrength, etc, and value is the value that is returned from the sensors - not yet added).

The problem I am having is I am reading the incomingData from the controlUnit as a String so that I can use the indexOf() function to separate the incomingData into commandType (either commandWord or variableRequest) and commandValue. I am then trying to conver the command Value into a byte array so that each of the motorUnits (there will be 11) can read the byte that is specific to it.

Code and error is posted below.

G:\My Drive\arduinoProjects\testMotorUnit\_2.0wButton\testMotorUnit\_2.0wButton.ino: In function 'void loop()':  
G:\My Drive\arduinoProjects\testMotorUnit\_2.0wButton\testMotorUnit\_2.0wButton.ino:73:62: error: invalid cast from type 'arduino::String' to type 'byte {aka unsigned char}'  
commandWord[i] = byte(commandValue.substring(i));  
^

exit status 1

Compilation error: invalid cast from type 'arduino::String' to type 'byte {aka unsigned char}'

```arduino
/*
Motor Units

need to change Unit number for each one
*/

#include <Arduino.h>
#include <WiFiNINA.h>
#include "arduino_secrets.h"
#include "utility/wifi_drv.h" //only needed for onboard led.
//also will need battery libraries

//variables for network information
const char ssid[] = APssid;
const char pass[] = APpass;
IPAddress server(192,168,4,1);
unsigned long previousMillis = 0;
int interval = 5000;

//variable for motorUnits
const byte motorUnits = 11;
byte commandWord[motorUnits];
const String variableRequest[] = {"shutterStatus", "batteryLevel", "signalStrength", "tempSensor"};
float motorUnitStatus[sizeof(variableRequest)];

//variables for client information
String clientName = "motorUnit_0"; //This is the name of this board. It needs to be changed for each board (0, 1, 2, 3, etc).
WiFiClient client;

//variables for LED testing
const int ledPin = 2;
const int onboardLEDRed = 25;
const int onboardLEDGreen = 26;
const int onboardLEDBlue = 27;

//variables for Serial Monitor testing

String ServerMessage; // not sure what this is for.... it is never called in the code I am copying

void setup() {
  Serial.begin(9600);
  Serial.print("Begin setup() function | Line: "); Serial.println( __LINE__ );
  Serial.print("Connecting to AP network | Line: "); Serial.println( __LINE__ );
  WiFi.begin(ssid, pass); //I might need to use WiFi.config() to change the ip address of each board before calling WiFi.begin(). But, I am going to leave it as is for now and see what happens. It might all work out.
  while(WiFi.status() != WL_CONNECTED){
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to AP network with IP Address: "); Serial.print(WiFi.localIP()); Serial.print(" | Line: "); Serial.println( __LINE__ );
}

// The clientRequest() from the control board uses the following syntax: either <commandWord:xxxxxxxxxxx>, or <motorUnit_x:"variable"?> | It is expecting no response for commandWord and a response for motorUnit_x with the following syntax: <motorUnit_x:"variable":"value" | x is an int that changes for each function, "variable" is the variable type that is requested (shutterStatus, batteryLevel, etc), and value is a float returned from the sensors.
void loop() {
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval) {
    if(WiFi.status() == WL_CONNECTED){
      Serial.print("Connecting to Server | Line: "); Serial.println( __LINE__ );
      client.connect(server, 80);
      while(client.connected()){
        Serial.print("Connected to Server | Line: "); Serial.println( __LINE__ );
        String incomingData = client.readStringUntil('\r'); //read String until carriage return
        if(incomingData != "\0"){
          Serial.print("Received data from Server: "); Serial.print(incomingData); Serial.print(" | Line: "); Serial.println( __LINE__ );
          int index = incomingData.indexOf(':');
          String commandType = incomingData.substring(0, index);
          String commandValue = incomingData.substring(index +1);
          if(commandType == "commandWord"){
            for(int i=0; i<commandValue.length(); i++){
              commandWord[i] = byte(commandValue.substring(i, i++));
            }
            for(int i=0; i<sizeof(commandWord); i++){
              Serial.print(commandWord[i]);
            } 
          } else if(commandType == clientName){

          }
        }
      }
    }
  }
}

```

---

<div class="post-metadata">

**Author:** ![kenb4](https://avatars.discourse-cdn.com/v4/letter/k/bb73d2/32.png) [@kenb4](https://forum.arduino.cc/u/kenb4)\
**Post date:** [August 20, 2024, 3:44am UTC](https://forum.arduino.cc/t/convert-string-to-byte-getting-invalid-cast-error/1293536/2 "2024-08-20T03:44:41Z")

</div>

> [@](#):
>
> `commandValue.substring(i, i++)`

This is always an empty string, because `i++` increments after the value is taken: both arguments have the same value. In a similar situation, you might use `i + 1` -- the `for` loop already increments `i`.

Regardless, the result is another `String`: an object that you cannot simply convert to a `byte`, regardless of its length. Instead use [String::charAt](https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/charat/) which returns a single `char`. You don't even have to explicitly convert it after.

---

<div class="post-metadata">

**Author:** ![brandonstone](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/brandonstone/32/977807_2.png) [@brandonstone](https://forum.arduino.cc/u/brandonstone)\
**Post date:** [August 20, 2024, 4:25am UTC](https://forum.arduino.cc/t/convert-string-to-byte-getting-invalid-cast-error/1293536/3 "2024-08-20T04:25:10Z")

</div>

Thanks. The i++ is a typo. It is supposed to be i+1. I'll give that charAt a try tomorrow

---

<div class="post-metadata">

**Author:** ![brandonstone](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/brandonstone/32/977807_2.png) [@brandonstone](https://forum.arduino.cc/u/brandonstone)\
**Post date:** [August 20, 2024, 4:27am UTC](https://forum.arduino.cc/t/convert-string-to-byte-getting-invalid-cast-error/1293536/4 "2024-08-20T04:27:12Z")

</div>

Would I be able to use that charAt() in the same syntax and add the value directly to the byte commandWord array?

---

<div class="post-metadata">

**Author:** ![kenb4](https://avatars.discourse-cdn.com/v4/letter/k/bb73d2/32.png) [@kenb4](https://forum.arduino.cc/u/kenb4)\
**Post date:** [August 20, 2024, 6:19am UTC](https://forum.arduino.cc/t/convert-string-to-byte-getting-invalid-cast-error/1293536/5 "2024-08-20T06:19:41Z")

</div>

```cpp
  commandWord[i] = commandValue.charAt(i);

```

This works fine; but looking at it, it doesn't really do much. Copies a thing at `i` to another thing at `i`. A `String` holds (and provides several handy functions for) a bunch of `char`, which are close to `byte` anyway.

- Just `char` means a _signed_ `char`, not an `unsigned char`
- `char` is used for text:

```arduino
const char ssid[] = "mywifi";

```

- `unsigned char` is actually used for "smallest possible (unsigned) numeric type", 8 bits on almost everything nowadays: `0` to `255`
- if it's a number, it's clearer to use `uint8_t` or `int8_t`
- `byte` is an alias for `uint8_t`, which in turn is `unsigned char`

If you have

```cpp
byte b = 255;
char c = 65;
Serial.println(b); // size_t Print::println(unsigned char b, int base = DEC)
Serial.println(c); // size_t Print::println(char c)

```

To a computer, everything is a bunch of bits. But the first `println` treats those bits as its numeric value, printed as a decimal number by default. The second treats the number as the code point for a character, and prints an '`A`' in this case. Similarly

```cpp
Serial.print(commandWord[i]); // number
Serial.print(commandValue.charAt(i)); // character

```

The ASCII value of '`1`' is `49`. What do you really want to see? What do you plan to do with it?

---

<div class="post-metadata">

**Author:** ![brandonstone](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/brandonstone/32/977807_2.png) [@brandonstone](https://forum.arduino.cc/u/brandonstone)\
**Post date:** [August 20, 2024, 12:04pm UTC](https://forum.arduino.cc/t/convert-string-to-byte-getting-invalid-cast-error/1293536/6 "2024-08-20T12:04:13Z")

</div>

The purpose of this code is to tell 11 motors at different locations around the house to open/close window shutters. The commandWord is a byte array with 11 indexes. So, when the I press a button on the controlUnit, it updates the commandWord and sends it to all 11 motorUnits. The motorUnits each look at a specific index in the commandWord, and open/closes. So, technically, the commandWord could be a bool array, but i had an idea that i could use the remaining 7 bits of each index byte (using bitWrite() for each command on the controlUnit) for additional commands (treating each byte as an 8bit bool array), and use bitRead() to determine the full command so up to 8 commands to each motorUnit per commandWord.

I suppose I can make the commandWord a char array. Since I'm using a for loop to print each index to Serial and client anyway, I dont think it will make much difference for the controlUnit code.

(Could you point me to a reference, such as Arduino Variable Types for Dummies, that could help me understand the int\_8t, uint\_8t, etc variables. I -kinda- understand that int\_8t is the same as int (I think), but I dont understand why a person would use int\_8t instead of int.)

---

<div class="post-metadata">

**Author:** ![oqibidipo](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/oqibidipo/32/221794_2.png) [@oqibidipo](https://forum.arduino.cc/u/oqibidipo)\
**Post date:** [August 20, 2024, 2:48pm UTC](https://forum.arduino.cc/t/convert-string-to-byte-getting-invalid-cast-error/1293536/7 "2024-08-20T14:48:51Z")

</div>

> [@kenb4](#):
>
> Just `char` means a _signed_ `char`, not an `unsigned char`

Plain `char` can be signed or unsigned depending on the architecture, but it is never the same type as `signed char` or `unsigned char`. On ARM targets it is usually unsigned.

---

<div class="post-metadata">

**Author:** ![gcjr](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/gcjr/32/314015_2.png) [@gcjr](https://forum.arduino.cc/u/gcjr)\
**Post date:** [August 20, 2024, 6:27pm UTC](https://forum.arduino.cc/t/convert-string-to-byte-getting-invalid-cast-error/1293536/8 "2024-08-20T18:27:54Z")

</div>

> [@brandonstone](#):
>
> The commandWord is a byte array with 11 indexes.

look this over. don't know how you intend set/clr control byte

```arduino
// 

enum { Off = HIGH, On = LOW };

byte PinLeds [] = { 10, 11, 12 };
byte PinButs [] = { A1, A2, A3 };
#define Nbut sizeof(PinButs)

byte butState [Nbut];

#define Nbyte Nbut
unsigned int ctrlBytes [Nbyte];;

// -----------------------------------------------------------------------------
#define NoBut -1
int
chkButtons ()
{
    for (unsigned n = 0; n < sizeof(PinButs); n++) {
        byte but = digitalRead (PinButs [n]);

        if (butState [n] != but) {
            butState [n] = but;

            delay (10); // debounce

            if (On == but)
                return n;
        }
    }
    return NoBut;
}

// -----------------------------------------------------------------------------
void
processCmd (
    unsigned int *cmd )
{
    for (unsigned i = 0; i < Nbyte; i++) {
        digitalWrite (PinLeds [i], cmd [i] & 1);
    }
}

// -----------------------------------------------------------------------------
void
loop ()
{
    int but = chkButtons ();
    if (NoBut != but) {
        ctrlBytes [but] ^= 1; // exclusive-OR, toggle control bit
    }

    processCmd (ctrlBytes);
}

// -----------------------------------------------------------------------------
void
setup ()
{
    Serial.begin (9600);

    for (unsigned n = 0; n < sizeof(PinButs); n++) {
        pinMode (PinButs [n], INPUT_PULLUP);
        butState [n] = digitalRead (PinButs [n]);
    }

    for (unsigned n = 0; n < sizeof(PinLeds); n++) {
        digitalWrite (PinLeds [n], Off);
        pinMode (PinLeds [n], OUTPUT);
    }
}

```

---

<div class="post-metadata">

**Author:** ![kenb4](https://avatars.discourse-cdn.com/v4/letter/k/bb73d2/32.png) [@kenb4](https://forum.arduino.cc/u/kenb4)\
**Post date:** [August 22, 2024, 7:28am UTC](https://forum.arduino.cc/t/convert-string-to-byte-getting-invalid-cast-error/1293536/9 "2024-08-22T07:28:47Z")

</div>

> [@brandonstone](#):
>
> I suppose I can make the commandWord a char array.

In that case, there is no need to make a copy, because the `commandValue` `String` already contains a `char` array. You can even using the `[]` operators to read and write the elements; the `charAt` and `setCharAt` methods are equivalent. A little less code, and save some memory.

> [@](#):
>
> I -kinda- understand that int\_8t is the same as int (I think), but I dont understand why a person would use int\_8t instead of int

Both are integers, but `int` is at least 16 bits, used for "human-scale" counting and integer math. It used to be usually the "natural word size" of the CPU, so e.g.

- 16 on 8-bit AVR
- 32 on ESP32
- 32 on modern 64-bit desktop/laptop CPUs, since 64 would "waste too many bits"

In contrast, `int8_t` is 8 bits everywhere. For data structures and wire protocols where you need specific sizes, you use `int`_N_`_t`, signed or unsigned. Further, on a rare CPU doesn't support that size for whatever reason, you'll know right away because your code won't compile there.

---

<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:** [February 18, 2025, 7:29am UTC](https://forum.arduino.cc/t/convert-string-to-byte-getting-invalid-cast-error/1293536/10 "2025-02-18T07:29:17Z")

</div>

Closed on February 18, 2025, 7:29am UTC

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.
