You are on page 1of 21

CSE 121 – Advanced C Programming

Dr. Nawal El Boghdady


nawal.elboghdady@eui.edu.eg

WEEK 8: UNIONS AND BIT OPERATIONS


Outline
Unions
• union Declarations
• union Operations
• Initializing unions in Declarations
Bit Operations
• Bitwise Operators
• Displaying an Unsigned Integer’s Bits
• Using the Bitwise AND, Inclusive OR, Exclusive OR and Complement Operators
• Using the Bitwise Left- and Right-Shift Operators
• Bitwise Assignment Operators
Unions
Recall the Student Names and
GPAs problem
We want to store the names and GPAs of the students in this class
•We can either use 2 arrays…
• char * name[68];
• float gpa[68];

•Or we can use a struct, with members:


• struct student{
char * name;
float gpa;
};

Or we can use a union…


Unions
Unions are data structures that look like structs, but their members shareTHE SAME memory location! This
means that only one of the members will have a value at any given time. This is useful when the same
piece of information has different representations.

The following union has two members—int x and double y:

union number {
◦ int x;
◦ double y;

};
Union Example
union data • Important: The compiler does not test if
{ the data is being read in the correct
int idata ; format.
float fdata ; union data d; d.idata=10; float f=d.fdata; /∗
will give junk∗/
6 char ∗sdata ;
}
d1 . i d a t a =10;
d1 . f d a t a =3.14F ;
d1 . sdata="hello world" ;

• The size of the union variable is equal


to the size of its largest element.
Union Example 2
Output is implementation dependent!
Union Output
Bit Operations
Bitwise Operators

•Data internally represented as sequences of


bits (0 or 1).
•1 byte = 8 bits, which is the typical storage
OR
unit for a char variable.
•The bitwise operators are used to
manipulate the bits of integral operands,
both signed and unsigned, though unsigned
integers are typically used.
•Bitwise data manipulations are machine-
dependent.
Bitwise Operators
Left shift and right shift
‘(x<<y)’ shifts bits by y locations to the left and is equivalent to multiplying x with 2^y (2 raised to
power y

‘(x>>y)‘ is equivalent to dividing x with 2^y or shifting the bits y units to the right
Bitwise Operators
Useful in programming for operations such as
logical indexing used to subset data

E.g. if I want to select all names whose age is <


25 and weight > 190
Demonstrating left and right
shift
Bitwise AND, OR, XOR
Output
Bitfields
Bitfields
You can specify the number of bits in which to store an unsigned or signed integral

member of a struct or union. Known as bit fields, these enable better memory utilization

by storing data in the minimum number of bits required. Bit field members

typically are declared as int or unsigned int.


Example
Example Continued
Output

You might also like