Code Implementation
Comprehensive Memory Unit Conversion Library
#ifndef MEMORY_CONVERSION_H
#define MEMORY_CONVERSION_H
#include <stdint.h>
// Memory Unit Enumeration
typedef enum {
BYTE_UNIT = 1,
KILOBYTE_UNIT = 2,
MEGABYTE_UNIT = 3,
GIGABYTE_UNIT = 4
} MemoryUnit;
// Memory Conversion Function Prototypes
uint64_t convert_memory_units(
uint64_t value,
MemoryUnit source_unit,
MemoryUnit target_unit
);
double calculate_memory_percentage(
uint64_t used_memory,
uint64_t total_memory
);
void display_memory_info(uint64_t bytes);
#endif
Implementation Details
Complete Conversion Implementation
#include "memory_conversion.h"
#include <stdio.h>
uint64_t convert_memory_units(
uint64_t value,
MemoryUnit source_unit,
MemoryUnit target_unit
) {
// Conversion matrix
const uint64_t conversion_factors[] = {
1, // Byte
1024, // Kilobyte
1024 * 1024, // Megabyte
1024 * 1024 * 1024 // Gigabyte
};
// Convert to base unit (bytes)
uint64_t bytes = value * conversion_factors[source_unit - 1];
// Convert from bytes to target unit
return bytes / conversion_factors[target_unit - 1];
}
void display_memory_info(uint64_t bytes) {
const char* units[] = {"B", "KB", "MB", "GB"};
double converted_value = bytes;
int unit_index = 0;
while (converted_value >= 1024 && unit_index < 3) {
converted_value /= 1024;
unit_index++;
}
printf("Memory: %.2f %s\n", converted_value, units[unit_index]);
}
Conversion Workflow
graph TD
A[Input Value] --> B[Select Source Unit]
B --> C[Convert to Bytes]
C --> D[Select Target Unit]
D --> E[Convert from Bytes]
E --> F[Output Converted Value]
Practical Usage Example
#include <stdio.h>
#include "memory_conversion.h"
int main() {
uint64_t memory_value = 2048; // 2048 MB
// Convert 2048 MB to GB
uint64_t gb_value = convert_memory_units(
memory_value,
MEGABYTE_UNIT,
GIGABYTE_UNIT
);
printf("2048 MB is equal to %lu GB\n", gb_value);
// Display memory information
display_memory_info(memory_value * 1024 * 1024);
return 0;
}
Error Handling and Validation
Scenario |
Handling Strategy |
Overflow |
Return maximum possible value |
Negative Input |
Return 0 or raise error |
Unsupported Units |
Implement default conversion |
- Use inline functions for small conversions
- Implement bitwise operations
- Cache frequently used conversion results
- Minimize function call overhead
LabEx Best Practices
- Validate input ranges
- Use consistent error handling
- Implement comprehensive unit testing
- Document conversion assumptions clearly
Compilation and Usage
## Compile the memory conversion utility
gcc -o memory_converter memory_conversion.c
## Run the utility
./memory_converter