blob: cf18b49026f72b7f282ae2c3e93239b8456652f1 [file] [edit]
#include "shell.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define decode_hex_digit(c) ((c) >= '0' && (c) <= '9' ? (c) - '0' : (c) >= 'a' && (c) <= 'f' ? (c) - 'a' + 10 : (c) >= 'A' && (c) <= 'F' ? (c) - 'A' + 10 : -1)
static int decode_hex_byte(const char *hex, error_message_t *error_message) {
int high = decode_hex_digit(hex[0]);
int low = decode_hex_digit(hex[1]);
if (high < 0 || low < 0) {
error_message_set_format(error_message, "invalid hex character '%c'", hex[high < 0 ? 0 : 1]);
return -1;
}
return (high << 4) | low;
}
zip_uint8_t *decode_hex(const char *hex, error_message_t *error_message) {
if (!hex) {
error_message_set(error_message, "hex string is NULL");
return NULL;
}
size_t len = strlen(hex);
if (len % 2 != 0) {
error_message_set(error_message, "hex string has odd length");
return NULL;
}
size_t decoded_len = len / 2;
zip_uint8_t *decoded = malloc(decoded_len);
if (!decoded) {
error_message_set(error_message, "memory allocation failed");
return NULL;
}
for (size_t i = 0; i < decoded_len; i++) {
int byte = decode_hex_byte(hex + 2 * i, error_message);
if (byte < 0) {
free(decoded);
return NULL;
}
decoded[i] = (zip_uint8_t)byte;
}
return decoded;
}
void print_hex(const zip_uint8_t *data, size_t len) {
for (size_t i = 0; i < len; i++) {
printf("%02x", (unsigned char)data[i]);
}
printf("\n");
}