SUPPORT-8592. Добавлен hex_to_bin()
This commit is contained in:
parent
17d40a464e
commit
a221960fbf
2 changed files with 50 additions and 0 deletions
|
|
@ -49,3 +49,51 @@ str_t_to_string(const str_t* str)
|
|||
|
||||
return string;
|
||||
}
|
||||
|
||||
|
||||
static int
|
||||
char2int(char input)
|
||||
{
|
||||
if (input >= '0' && input <= '9') {
|
||||
return input - '0';
|
||||
}
|
||||
|
||||
if (input >= 'A' && input <= 'F') {
|
||||
return input - 'A' + 10;
|
||||
}
|
||||
|
||||
if (input >= 'a' && input <= 'f') {
|
||||
return input - 'a' + 10;
|
||||
}
|
||||
|
||||
LOG_ERROR("char2int exit with error: invalid argument, '%c'", input);
|
||||
assert("char2int exit with error: invalid argument");
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
int
|
||||
hex_to_bin(const str_t* hex, /*out*/ str_t* bin)
|
||||
{
|
||||
bin->len = hex->len / 2;
|
||||
bin->data = malloc(bin->len + 1);
|
||||
if (bin->data == NULL) {
|
||||
LOG_ERROR("Could not allocate memory for bin value (%zd bytes)", bin->len + 1);
|
||||
goto error;
|
||||
}
|
||||
|
||||
const char* src = hex->data;
|
||||
char* dst = bin->data;
|
||||
|
||||
while (*src && src[1]) {
|
||||
*(dst++) = char2int(*src)*16 + char2int(src[1]);
|
||||
src += 2;
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
||||
error:
|
||||
str_t_clear(bin);
|
||||
LOG_ERROR("hex2bin exit with error");
|
||||
return -1;
|
||||
}
|
||||
|
|
@ -92,4 +92,6 @@ int str_t_copy(str_t* dst, const str_t* src);
|
|||
|
||||
char* str_t_to_string(const str_t* str);
|
||||
|
||||
int hex_to_bin(const str_t* hex, /*out*/ str_t* bin);
|
||||
|
||||
#endif // STR_T_H_INCLUDED
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue