Variables to byte arrays

Jan 28, 2016 at 9:09pm
Hi, need some help with converting variables into byte arrays for serial transmission on Arduino in each direction. I need to convert int, long, long long and float to byte arrays for transmission then back to those variables when received.

I am new to C/C++ but not programming in general and when I started searching I found a lot of conflicting approaches, arguments along with concerns about Endienness. I realize the importance of that, but as everything stays within the Arduino family, would Endienness be an issue?

This got me to thinking that I can't be the first ever to need these functions, so thought I would ask here about a libraries (free - I am retired) that might be available to cover this issue.

In other languages I program, I would just copy the actual byte values using Pointers to the variables, but cannot find any good examples like that in C/C++ - yet.

But a library set of all these functions in one place would sure be handy.

Thanks
Jan 28, 2016 at 9:25pm
What exactly do you mean by byte arrays?

Normally this processor "prints" C-strings via the serial port. To convert numeric value to a C-string you should be able to use the sprintf() function. To convert a C-string back to a number you should be able to use sscanf().

http://www.ladyada.net/learn/arduino/lesson4.html
Last edited on Jan 28, 2016 at 9:26pm
Jan 28, 2016 at 9:32pm
What is a byte array?? like an array of int or short?
Jan 29, 2016 at 3:23pm
>> What is a byte array?

It is an array of bytes. Or, as far as I can tell in Arduino an

byte anArr[32] = {0};
is equal to
unsigned char anArr[32] = {0};

But now moot, I have figured it out another way. Seems like the Arduino is a little too far from the true C++ to be useful to me here.

@jlb:
Seriously sprintf() and sscanf() ?
Did you read what I was trying to do? Passing data arrays between devices via serial.
Jan 29, 2016 at 3:46pm
Seriously sprintf() and sscanf() ?
Did you read what I was trying to do? Passing data arrays between devices via serial.

Yes, I was serious. You didn't define what you meant by byte array and since the Arduino normally "prints" and "receives" character strings, not "byte arrays", sprintf() and sscanf() are viable ways of converting "numbers" to and from strings.

Jan 29, 2016 at 4:04pm
Do you mean something like this ?
1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
using namespace std ; 


int main()
{
    int var = 5 ; 

    char byteArray[sizeof(var)]  ;
    memcpy(byteArray,(const char *)&var,sizeof(var));
}
Last edited on Jan 29, 2016 at 4:05pm
Topic archived. No new replies allowed.