Skip to content

Commit

Permalink
Adds string to hex to format_utils. (#421)
Browse files Browse the repository at this point in the history
  • Loading branch information
balazsracz authored Sep 4, 2020
1 parent 9ca2116 commit beb5f19
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 20 deletions.
45 changes: 25 additions & 20 deletions src/utils/format_utils.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@
#include "utils/macros.h"
#include "utils/format_utils.hxx"

/// Translates a number 0..15 to a hex character.
/// @param nibble input number
/// @return character in 0-9a-f
static char nibble_to_hex(unsigned nibble)
{
return nibble <= 9 ? '0' + nibble : 'a' + (nibble - 10);
}

char* unsigned_integer_to_buffer_hex(unsigned int value, char* buffer)
{
int num_digits = 0;
Expand All @@ -50,16 +58,8 @@ char* unsigned_integer_to_buffer_hex(unsigned int value, char* buffer)
do
{
HASSERT(num_digits >= 0);
unsigned int tmp2 = tmp % 16;
if (tmp2 <= 9)
{
buffer[num_digits--] = '0' + tmp2;
}
else
{
buffer[num_digits--] = 'a' + (tmp2 - 10);
}
tmp /= 16;
buffer[num_digits--] = nibble_to_hex(tmp & 0xf);
tmp >>= 4;
} while (tmp);
HASSERT(num_digits == -1);
return ret;
Expand All @@ -80,16 +80,8 @@ char* uint64_integer_to_buffer_hex(uint64_t value, char* buffer)
do
{
HASSERT(num_digits >= 0);
uint64_t tmp2 = tmp % 16;
if (tmp2 <= 9)
{
buffer[num_digits--] = '0' + tmp2;
}
else
{
buffer[num_digits--] = 'a' + (tmp2 - 10);
}
tmp /= 16;
buffer[num_digits--] = nibble_to_hex(tmp & 0xf);
tmp >>= 4;
} while (tmp);
HASSERT(num_digits == -1);
return ret;
Expand Down Expand Up @@ -237,6 +229,19 @@ string int64_to_string_hex(int64_t value, unsigned padding)
return ret;
}

string string_to_hex(const string &arg)
{
string ret;
ret.reserve(arg.size() * 2);
for (char c : arg)
{
uint8_t cc = static_cast<uint8_t>(c);
ret.push_back(nibble_to_hex((cc >> 4) & 0xf));
ret.push_back(nibble_to_hex(cc & 0xf));
}
return ret;
}

string mac_to_string(uint8_t mac[6], bool colon)
{
string ret;
Expand Down
6 changes: 6 additions & 0 deletions src/utils/format_utils.hxx
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,12 @@ string uint64_to_string_hex(uint64_t value, unsigned padding = 0);
*/
string int64_to_string_hex(int64_t value, unsigned padding = 0);

/// Converts a (binary) string into a sequence of hex digits.
/// @param arg input string
/// @return string twice the length of arg with hex digits representing the
/// original data.
string string_to_hex(const string& arg);

/// Formats a MAC address to string. Works both for Ethernet addresses as well
/// as for OpenLCB node IDs.
///
Expand Down

0 comments on commit beb5f19

Please sign in to comment.