nostr_core_lib/nostr_core/utils.c

37 lines
842 B
C

/*
* NOSTR Core Library - Utilities
*
* General utility functions used across multiple NIPs
*/
#include "utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**
* Convert bytes to hexadecimal string
*/
void nostr_bytes_to_hex(const unsigned char* bytes, size_t len, char* hex) {
for (size_t i = 0; i < len; i++) {
sprintf(hex + i * 2, "%02x", bytes[i]);
}
hex[len * 2] = '\0';
}
/**
* Convert hexadecimal string to bytes
*/
int nostr_hex_to_bytes(const char* hex, unsigned char* bytes, size_t len) {
if (strlen(hex) != len * 2) {
return -1; // NOSTR_ERROR_INVALID_INPUT
}
for (size_t i = 0; i < len; i++) {
if (sscanf(hex + i * 2, "%02hhx", &bytes[i]) != 1) {
return -1; // NOSTR_ERROR_INVALID_INPUT
}
}
return 0; // NOSTR_SUCCESS
}