Converting byte array to long and long to byte array in specific position


I'm trying to work with byte arrays and pointers, as I need to extract from a byte array, which I had received and stored from an I2C connection, however from this array I would need to extract the last 4 bytes and converted to a long.

Also the opposite is required, where for instance I have another long and I need to stored in a different byte array (for my testing) so far I have this code

byte I2C_rev [7] ={0x07,0x043,0x40,0x00,0x23,0xAB,0x2F};
byte I2C_rev2 [7] ={0,0,0,0,0,0,0};
// Integer to use 2337583, 0x0023AB2F in hex, which is equal to 0x00, 0x23, 0xAB, 0x2F
// 0x07, size of the byte array
// 0x43 the I2C address
// 0x10 the Register (function to use)

byte msg_size, I2C_Address, Register;
long data;
long data2 = 214050;

void setup() {
//--- receive string, and put data from a pointer to a long variable ------
Serial.println ("ready");
delay (1000);

void loop() {

msg_size =I2C_rev[1];
Serial.println (" to extract from Byte array last 4 bytes and converted to long");
long intpos = (long)&I2C_rev+3;
Serial.println (*intpos);
Serial.println (data);
delay (1000);

//--------------- Store a string in to the byte array

Serial.println ("to store a long in the last 4 byte of the array");
I2C_rev[1]=0x07; //message size 7 bytes
I2C_rev[2]=0x042; //I2C address
I2C_rev[3]=0x25; //Register value

// to store the long number in to the last 4 bytes of the array

long intpos2 = (long)&I2C_rev2+3;
*intpos2 = data2;
long test;
Serial.println (*intpos2);
Serial.println (data2);


So far I have apparently been successful in the last part - storing the long in to the array, but not the extraction

Can anyone please help me


Looks like this is a problem:

long *intpos =(long*)&I2C_rev+3;

I think the compiler is interpreting the +3 as +3 longs, or 12 bytes.

This seems to work better:

long *intpos = (long*)&I2C_rev[3];

Also, it looks like you need to reverse the order of the bytes that make up the long.

Please keep the comments and code unambiguous as in the end the code is allways right :wink:

// 0x43 the I2C address

I2C_rev[2]=0x042; //I2C address

Couple of comments on pointers and arrays:

  • The first element in an array has an index of 0, not 1. So you probably want:
  msg_size =I2C_rev[0];
  • A leading zero in hex values like 0x043 is slightly confusing - only the last two digits will end up in a byte anyway.

  • Is the correct array being used here? Or should it be I2C_rev2? Also mind the indexes

  I2C_rev[1]=0x07; //message size 7 bytes