Bitwise operators

advertisement
C/C++ Training
Programming C/C++ on Eclipe
Trình bày : Ths HungNM
LOW-LEVEL PROGRAMMING



Bitwise operators.
Bitwise-Field structure
Other Low-Level Techniques
EcoSoftware
Training C/C++
2
Bitwise operators




Bitwise shift operators
Bitwise component And, Or
Using bitwise operators to access bits
Using bitwise operators to access Bit-Fields
EcoSoftware
Training C/C++
3
Bitwise operators



Bitwise shift operators
Using << (left shift) >> (right shift).
Example :
EcoSoftware
Training C/C++
4
Bitwise component


List the remaining bitwise components.
Symbol
Meaning
~
Bitwise component
&
Bitwise and
^
Bitwise exclusive or
|
Bitwise inclusive or
Example.
EcoSoftware
Training C/C++
5
Using bitwise operator to access bits

Setting a bit

Example : Setting bit 4 for i;

Clearing a bit

Testing a bit
EcoSoftware
Training C/C++
6
Using bitwise operator to access Bit-Fields

Modifying a bit-field.

Using bitwise and, bitwise or for modifying a bit field.

Example :

Retrieving a bit-field
The bit-field at the right end of number (in the least
significant bits),fetching its value easy.
 Example :
 Other you can first shift the bit-field to the end before
extracting the field using & operator.
 Example :

EcoSoftware
Training C/C++
7
Bit-Fields in structures

Using bit-fields we can define a C structure with
identical layout.



Example :
The number after each member indicate it length
of bit.
The type of bit-field must be either int, unsigned
int, signed int.
EcoSoftware
Training C/C++
8
Other Low-Level Techniques

Defining Machine-Dependent Types
The char type –by definition – occupies one byte, We
sometime treats character as bytes.
 Using theme to store data that’s not necessarily in
character form.
• typedef unsigned char BYTE;
 Depend on the machine x86 architecture make
extensive use of 16 bit words. That you can defines:
• typedef unsigned short WORD;

EcoSoftware
Training C/C++
9
Other Low-Level Techniques

Using pointer as address.
Create a pointer that represents is specific address
easy.
 We just cast an integer into a pointer.


Example :
BYTE *p;
 p = (BYTE *)0x1000 // p content address 0x1000

EcoSoftware
Training C/C++
10
Example : View memory information
EcoSoftware
Training C/C++
11
Example : View memory information
EcoSoftware
Training C/C++
12
Example : View memory information

Using gcc test it on an x86 with linux.
EcoSoftware
Training C/C++
13
End
• Thank You
EcoSoftware
Training C/C++
14
Download