String to byte[] and vice versa

Damn I feel such a retard. How difficult can this be?

Um, can you be a little more specific? A single line of code indicating what you are trying to do would be helpful? Are you asking how do I cast string to byte[] or how to get a byte * from a String object?

How hard can what be?

I want to encrypt a string. But before doing that I need to represent it as an array of byte.
For the String to byte[] part, I got this.

String message = "Hello World";
byte plain[message.length()];
message.getBytes(plain, message.length());

But I don't know how to do it the other way around.

The easiest thing would be to quit leaning on the crutch of the String class and use char arrays. Then you would have almost no work to do since you can just cast back and forth between char and byte.

Doing this with the String class might take a little more finesse.

Then how do I do the casting from byte[] to char[]?

edit:
char array = (char)byte_array;

is this correct?

zwaregast:
Then how do I do the casting from byte[] to char[]?

Why do you need to?

zwaregast:
I want to encrypt a string. But before doing that I need to represent it as an array of byte.
For the String to byte[] part, I got this.

String message = "Hello World";

byte plain[message.length()];
message.getBytes(plain, message.length());




But I don't know how to do it the other way around.

The below might be a way.

void setup(void)
{
}

void loop(void)
{
  byte byteArray[5];
  strcpy((char *)byteArray,"0123");
  String myString = String((char *)byteArray);
}
1 Like

zwaregast:
I want to encrypt a string. But before doing that I need to represent it as an array of byte.
For the String to byte[] part, I got this.

String message = "Hello World";

byte plain[message.length()];
message.getBytes(plain, message.length());




But I don't know how to do it the other way around.
...
Then how do I do the casting from byte[] to char[]?

First, "byte" is defined as "unsigned char". "char" is with sign.
If you use letters and numbers are all under value 127 ('A'=>65, 'z'=>122), so byte or char is the same in this case.

if you have an array of char or byte like your variable plain use atol(); convert from a string (vector of char) to long value

long x=atol(plain)