Hello!
My name is Stefan and I am new in this forum. I am from Germany and I like electronics and making things with arduino. My programming knowledge is somewhat limited but I do my best
I have a question about data conversion and a strange behavior I have observed in the following code. I´d like to convert a unsigned long number into an array of four bytes.
The conversion works fine but the reconversion into a unsigned long number is strange and I don´t understand it. I´m sure it is easy but I couldn´t find where the trick is.
Here is the code:
byte timearray[4];
unsigned long zeit;
unsigned long zeit2;
void setup() {
 Serial.begin(9600);
}
void loop() {
  zeit = 0xFFAABB11;
  Serial.print("Time: ");
  Serial.println(zeit, HEX);
  byte_con(zeit);
  Serial.print ("0. Byte: ");
  Serial.println (timearray[0], HEX);
  Serial.print ("1. Byte: ");
  Serial.println (timearray[1], HEX);
  Serial.print ("2. Byte: ");
  Serial.println (timearray[2], HEX);
  Serial.print ("3. Byte: ");
  Serial.println (timearray[3], HEX);
  Serial.println() ;
  Serial.print ("0. Byte (weighted): ");
  Serial.println (timearray[0], HEX);
  Serial.print ("1. Byte (weighted): ");
  Serial.println (timearray[1] * 0x100, HEX);
  Serial.print ("2. Byte (weighted): ");
  Serial.println (timearray[2] * 0x10000, HEX);
  Serial.print ("3. Byte (weighted): ");
  Serial.println (timearray[3] * 0x1000000, HEX);
  Serial.println ();
  Serial.print ("2. Byte (weighted and corrected): ");
  Serial.println (((timearray[1] * 0x100)- 0xFFFF0000), HEX);
  zeit2 = timearray[0] + ((timearray[1] * 0x100)- 0xFFFF0000) + ( timearray[2] * 0x10000) + (timearray[3] * 0x1000000);
  Serial.println();
  Serial.print ("Zeit2 (reconstructed): "); Â
  Serial.println (zeit2, HEX);
  Serial.println();
  Serial.println();
  while (true){
   };
}
void byte_con (unsigned long zahl){
Â
  unsigned long a = zahl % 0x100;
  unsigned long b = (zahl % 0x10000 - a)/0x100;
  unsigned long c = (zahl % 0x1000000 - (a + b))/0x10000;
  unsigned long d = (zahl % 0x100000000 - (a + b + c))/0x1000000;
  timearray[0] = byte (a);
  timearray[1] = byte (b);
  timearray[2] = byte (c);
  timearray[3] = byte (d);
  }
The results in the console are:
Time: FFAABB11
0. Byte: 11
-
Byte: BB
-
Byte: AA
-
Byte: FF
-
Byte (weighted): 11
-
Byte (weighted): FFFFBB00
-
Byte (weighted): AA0000
-
Byte (weighted): FF000000
-
Byte (weighted and corrected): BB00
Zeit2 (reconstructed): FFAABB11
Why is the second byte FFFFBB00 and not BB00 and why do I have to correct it by substracting 0xFFFF0000 to get the correct value. I assume it is related to the data types. But what is the reason? Could someone help me in this issue.
Best regards
Stefan
Test_Byte_Conversion.ino (1.67 KB)