Simple training demonstration to show the use of union and structure

Dependencies:   USBDevice mbed

Fork of OddExample1 by Jon Fuge

Files at this revision

API Documentation at this revision

Comitter:
jf1452
Date:
Tue Nov 26 14:53:06 2013 +0000
Parent:
9:0add51bbe65d
Commit message:
Odd Example 2 using union and structure

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
diff -r 0add51bbe65d -r 6c0cd51df4df main.cpp
--- a/main.cpp	Tue Nov 26 14:23:51 2013 +0000
+++ b/main.cpp	Tue Nov 26 14:53:06 2013 +0000
@@ -1,24 +1,31 @@
 /*******************************************************************************
 * This program demonstrates determines if a number is odd or even              *
-*                                                                              *
-* Jon Fuge                                                                     *
-* V1.0 26/11/2013 First issue of code                                          *
+* Jon Fuge V1.0 26/11/2013 First issue of code                                 *
 *******************************************************************************/
-
 #include "mbed.h"
 #include "USBSerial.h"
- 
-USBSerial serial; //Virtual serial port over USB. Use Teraterm as the interface
+
+union byte // Define new type “BYTE”
+{
+    char Byte; // Use this to map a byte
+    struct {
+       char Odd:    1; // this is the same as Bit0
+       char Others: 7; // Just pad the rest of the bits
+    };
+};
+
+USBSerial serial; // Virtual serial port over USB. Use Teraterm as the interface
 
 int main() {
-   char cMyNumber = 53; // Set it to an odd number
+   byte cMyNumber;      // Declare variable cMyNumber
+   cMyNumber.Byte = 53; // Set it to an odd number
 
    wait (10); // Wait 10 seconds to connect port
    
-   if ((cMyNumber & 0x01) == 1)
-      serial.printf("%i is odd\n\r", cMyNumber);
+   if (cMyNumber.Odd == 1)
+      serial.printf("%i is odd\n\r", cMyNumber.Byte);
    else
-      serial.printf("%i is even\n\r", cMyNumber);
+      serial.printf("%i is even\n\r", cMyNumber.Byte);
 
    for(;;) {} // Loop forever
 }
\ No newline at end of file