core: add functions to calculate the length of an int
This commit is contained in:
38
core/misc.c
Normal file
38
core/misc.c
Normal file
@@ -0,0 +1,38 @@
|
||||
#include <blue/core/misc.h>
|
||||
|
||||
#define LENGTH_RET(v, boundary, len) \
|
||||
if ((v) < (boundary)) \
|
||||
return (len);
|
||||
|
||||
size_t b_int_length(intptr_t v)
|
||||
{
|
||||
size_t len = 0;
|
||||
if (v < 0) {
|
||||
v *= -1;
|
||||
len++;
|
||||
}
|
||||
|
||||
return len + b_uint_length(v);
|
||||
}
|
||||
|
||||
size_t b_uint_length(uintptr_t v)
|
||||
{
|
||||
LENGTH_RET(v, 10, 1);
|
||||
LENGTH_RET(v, 100, 2);
|
||||
LENGTH_RET(v, 1000, 3);
|
||||
LENGTH_RET(v, 10000, 4);
|
||||
LENGTH_RET(v, 100000, 5);
|
||||
LENGTH_RET(v, 1000000, 6);
|
||||
LENGTH_RET(v, 10000000, 7);
|
||||
LENGTH_RET(v, 100000000, 8);
|
||||
LENGTH_RET(v, 1000000000, 9);
|
||||
LENGTH_RET(v, 10000000000, 10);
|
||||
|
||||
size_t len = 0;
|
||||
while (v > 0) {
|
||||
v /= 10;
|
||||
len++;
|
||||
}
|
||||
|
||||
return len;
|
||||
}
|
||||
Reference in New Issue
Block a user