Integer to char array and back. I'm missing something small!


so here code:
code: [select]

//function declaration
void int2bytes(int, char[]);
float int2float(int, float);
int bytes2int(char[]);
float bytes2float(char[]);

void setup()
{
  serial.begin(19200);
}

void loop()
{
  //test integers
  int i1 = 13106; //hex 33:32
  int i2 = 13181; //hex 33:7d
 
  //blank char arrays
  char result1[2] = {};
  char result2[2] = {};
 
  //convert integers chars
  int2bytes(i1, result1);
  int2bytes(i2, result2);
 
  serial.println(result1[1],hex);
  serial.println(result1[2],hex);
  delay(2000);
  serial.println(result2[1],hex);
  serial.println(result2[2],hex);
  delay(1000);
 
  serial.println(bytes2int(result1)); //convert int
  serial.println(bytes2int(result2)); //convert int
 
  delay(1000000); //stop repeating
}

void int2bytes(int integer, char bytes[])
{
  char high = (integer >> 8) & 0xff;
  char low  = integer & 0xff;
  //serial.println(high,hex);
  //serial.println(low,hex);
  delay(1000);
  bytes[1] = high;
  bytes[2] = low;
}

/*
this function take 2 bytes in array (little endian format) , convert them integer returned.
*/
int bytes2int(char bytes[])
{
  int i;
  memcpy(&i, bytes, sizeof(int));
  return i;
}

/*
this function take 4 bytes in array (little endian format) , convert them float returned.
*/
float bytes2float(char bytes[])
{
  float f;
  memcpy (&f, bytes, sizeof(float));
  return f;
}

and here getting result, can see integers not same original input
code: [select]

33
32
33
7d
13056
13106

why doing bit shifting extract bytes, , not doing bit shifting reassemble bytes?


Arduino Forum > Using Arduino > Programming Questions > Integer to char array and back. I'm missing something small!


arduino

Comments

Popular posts from this blog

Convierte tu Raspberry en un NAS. Firmware fvdw-sl 15.3 - Raspberry Pi Forums

How to format a Get Request

avrdude: verification error, first mismatch at byte 0x0000 0x0c != 0x62