Monday, June 9, 2014

Arduino - Cast Int to Byte - What happens?

For a project I need to spread a 16-bit unsigned integer across one byte variable and two 1-bit variables, all of which will be written to pins. The reason is not important, but I needed to know what happens to the byte value when I cast it to the byte variable. I understand that it will be truncated, but what will? The higher 8-bits or the lower 8-bits?

To find out, I wrote a quick program with a lot of clear text output.


// cast test by Jordan
// Test truncation of variables from one type to another
// most importatntly: int to byte

unsigned int intVar = 0x4080; // will it truncate to 01000000 or 10000000?
byte byteVar = 0x33;
void setup(){
  Serial.begin(9600);
  Serial.print("hello world.");
  Serial.println();
  Serial.println();

}

void loop(){
  Serial.println("integer variable equals: ");
  Serial.println(intVar, BIN); // print variable in binary
  Serial.println();
  Serial.println("byte variable equals: ");
  Serial.println(byteVar, BIN);
  Serial.println(".");
  Serial.println("..");
  Serial.println("...");
  byteVar = (byte)intVar;
  Serial.println("byte variable now equals: ");
  Serial.println(byteVar, BIN);
  while(1){} // loop forever
}

Then I uploaded it to my Arduino Nano and opened the serial monitor. I then uploaded it to my Teensy 2.0 to double check the code across platforms. Teensy is a little different in some aspects, so I had to make sure. They both output exactly the same thing:

Serial monitor output:

"hello world.
integer variable equals:
100000010000000
byte variable equals:
110011
.
..
...
byte variable now equals:
10000000"

These are the exact results that I wanted to see. I may continue on with more programming now...

EDIT: Further testing proves that the same theory does NOT hold true with booleans. (get it? "true") I had hoped that the boolean could be used to store a 1-bit number, but it turns out they are actually some sort of integer in disguise! I will have to figure out some fast way to manipulate individual bits...

No comments:

Post a Comment