Number Conversion Basics
Introduction to Number Conversion
Number conversion is a fundamental operation in programming that involves transforming numbers between different representations or number systems. In C programming, developers frequently need to convert numbers between various formats, such as decimal, binary, hexadecimal, and string representations.
Number Systems Overview
Number System |
Base |
Representation |
Example |
Decimal |
10 |
0-9 |
42 |
Binary |
2 |
0-1 |
101010 |
Hexadecimal |
16 |
0-9, A-F |
0x2A |
Common Conversion Functions in C
C provides several built-in functions for number conversion:
atoi()
: Converts string to integer
strtol()
: Converts string to long integer
sprintf()
: Converts number to string
snprintf()
: Safely converts number to string with buffer size control
Memory Representation
graph TD
A[Integer] --> B[Signed/Unsigned]
A --> C[32-bit/64-bit]
B --> D[Two's Complement]
C --> E[Memory Layout]
Basic Conversion Example
#include <stdio.h>
#include <stdlib.h>
int main() {
// String to integer conversion
char *str = "123";
int num = atoi(str);
printf("Converted number: %d\n", num);
// Integer to string conversion
char buffer[20];
snprintf(buffer, sizeof(buffer), "%d", num);
printf("Converted string: %s\n", buffer);
return 0;
}
Key Considerations
- Always validate input before conversion
- Check for potential overflow
- Use appropriate conversion functions
- Consider endianness in low-level conversions
At LabEx, we emphasize understanding these fundamental conversion techniques to build robust and efficient C programs.