first version of m06e01
This commit is contained in:
41
module06/ex01/math.c
Normal file
41
module06/ex01/math.c
Normal file
@@ -0,0 +1,41 @@
|
||||
#include "header.h"
|
||||
|
||||
void int_to_hex_string(uint64_t value, char *out, uint8_t num_digits) { // num_digits : number of digit of the output, ex 2 for 3FF (1023) -> FF
|
||||
for (uint8_t i = 0; i < num_digits; ++i) {
|
||||
uint8_t shift = (num_digits - 1 - i) * 4;
|
||||
out[i] = INT_TO_HEX_CHAR((value >> shift) & 0x0F);
|
||||
}
|
||||
out[num_digits] = '\0';
|
||||
}
|
||||
|
||||
void int_to_string_base(uint64_t value, char *buffer, uint8_t base) { // buffer must have the right size
|
||||
if (base < 2 || base > 36) {
|
||||
buffer[0] = '\0'; // unsupported base
|
||||
return;
|
||||
}
|
||||
|
||||
// handle zero case
|
||||
if (value == 0) {
|
||||
buffer[0] = '0';
|
||||
buffer[1] = '\0';
|
||||
return;
|
||||
}
|
||||
|
||||
uint8_t size = 0;
|
||||
uint64_t copy = value;
|
||||
|
||||
while (copy) {
|
||||
copy /= base;
|
||||
size++;
|
||||
}
|
||||
|
||||
buffer[size] = '\0'; // null-terminate the string
|
||||
size--; // adjust index for last digit
|
||||
|
||||
while (value) {
|
||||
uint8_t digit = value % base;
|
||||
buffer[size] = digit < 10 ? ('0' + digit) : ('A' + digit - 10);
|
||||
value /= base;
|
||||
size--;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user