Bit:
Byte:
int
, char
, etc.) is measured in bytes.Size of Data Types (in bytes):
char
: 1 byte (8 bits).int
: Typically 4 bytes (32 bits) on most systems.float
: Typically 4 bytes.double
: Typically 8 bytes.pointer
: Typically 8 bytes on 64-bit systems, 4 bytes on 32-bit systems.Use sizeof()
to determine the size of any data type in your system:
printf("Size of int: %lu bytes\\\\n", sizeof(int));
How Data is Stored in Memory:
int
has 4 bytes (32 bits), which are stored consecutively in memory, starting from the least significant byte in little-endian systems or the most significant byte in big-endian systems.Endianness:
Example:
int num = 0x12345678;
Bitwise Operations in C:
&
): Used to clear bits.|
): Used to set bits.^
): Used to toggle bits.~
): Used to flip bits.<<
): Shifts bits to the left (multiplies by 2).>>
): Shifts bits to the right (divides by 2).Example:
int x = 5; // 00000101 in binary
int y = x << 1; // Left shift: 00001010 (5 * 2 = 10)
Bit Masking:
Used to manipulate specific bits in a byte or word.
Example: Set the 3rd bit of a number.
x |= (1 << 2); // Sets the 3rd bit of x to 1.