utils: Added chunk_to_dec() function

This commit is contained in:
Andreas Steffen
2023-11-13 12:39:10 +01:00
committed by Tobias Brunner
parent 9381559754
commit d72d0c0dfa
3 changed files with 131 additions and 0 deletions
+66
View File
@@ -1,5 +1,6 @@
/*
* Copyright (C) 2008-2019 Tobias Brunner
* Copyright (C) 2023 Andreas Steffen
* Copyright (C) 2005-2006 Martin Willi
* Copyright (C) 2005 Jan Hutter
*
@@ -744,6 +745,71 @@ chunk_t chunk_to_base32(chunk_t chunk, char *buf)
return chunk_create(buf, len * 8 / 5);
}
/**
* Described in header.
*/
chunk_t chunk_to_dec(chunk_t chunk, char *buf)
{
int len, i, i_buf, i_bin = 0;
uint16_t remainder;
chunk_t bin;
/* Determine the number of needed decimal digits:
* 10^len > 2^(8*chunk.len) =>
* len > log(256) * chunk.len =>
* len > 2.4083 * chunk.len
*/
len = (int)(2.4083 * (double)chunk.len) + 1;
if (!buf)
{
buf = malloc(len + 1);
}
i_buf = len;
buf[i_buf] = '\0';
bin = chunk_clone(chunk);
while (i_bin < bin.len)
{
remainder = 0;
for (i = i_bin; i < bin.len; i++)
{
remainder = bin.ptr[i] + (remainder << 8);
if (remainder < 10)
{
remainder = bin.ptr[i];
bin.ptr[i] = 0;
if (i == i_bin)
{
i_bin++;
}
}
else
{
bin.ptr[i] = remainder / 10;
remainder %= 10;
}
}
if (i_buf > 0)
{
buf[--i_buf] = 0x30 + remainder;
}
}
chunk_free(&bin);
/* align decimal number to the start of the string */
if (i_buf > 0)
{
len -= i_buf;
for (i = 0; i <= len; i++)
{
buf[i] = buf[i + i_buf];
}
}
return chunk_create(buf, len);
}
/**
* Described in header.
*/
+13
View File
@@ -1,5 +1,6 @@
/*
* Copyright (C) 2008-2019 Tobias Brunner
* Copyright (C) 2023 Andreas Steffen
* Copyright (C) 2005-2008 Martin Willi
* Copyright (C) 2005 Jan Hutter
*
@@ -213,6 +214,18 @@ chunk_t chunk_from_base64(chunk_t base64, char *buf);
*/
chunk_t chunk_to_base32(chunk_t chunk, char *buf);
/**
* Convert a chunk of data to decimal encoding.
*
* The resulting string is '\\0' terminated, but the chunk does not include
* the '\\0'. If buf is supplied, it must hold at least (chunk.len * 2.41 + 1).
*
* @param chunk data to convert to decimal encoding
* @param buf buffer to write to, NULL to malloc
* @return chunk of encoded data
*/
chunk_t chunk_to_dec(chunk_t chunk, char *buf);
/**
* Free contents of a chunk
*/