hex2bin()
#
The hex2bin
function converts a hexadecimal string (hex
) into its binary representation, storing the result in a provided buffer (bf
). It uses a decoding table to map hexadecimal characters to their corresponding values and processes the input string two characters at a time to produce binary bytes.
Prototype
PUBLIC char *hex2bin(
char *bf,
int bfsize,
const char *hex,
size_t hex_len,
size_t *out_len
);
Parameters
Parameter |
Type |
Description |
---|---|---|
|
|
Pointer to the output buffer where the binary data will be stored. |
|
|
The size of the output buffer in bytes. |
|
|
The input hexadecimal string to be converted. |
|
|
The length of the input hexadecimal string. |
|
|
Pointer to a variable where the length of the binary output will be stored. Can be |
Return Value
Returns a pointer to the output buffer
bf
containing the binary data.Returns
NULL
if an error occurs (e.g., invalid hex character or buffer overflow).
Notes
Hexadecimal Decoding:
The function uses a decoding table (
base16_decoding_table1
) to map valid hexadecimal characters (0-9
,a-f
,A-F
) to their respective values.If an invalid character is encountered, the function stops processing.
Buffer Size Check:
Ensures that the binary data does not exceed the size of the output buffer (
bfsize
).
Even/Odd Logic:
Even indices of the hexadecimal input are processed as the high nibble (4 bits) of the binary byte, and odd indices as the low nibble.
Output Length:
The total number of bytes written to the output buffer is stored in
out_len
if it is notNULL
.
Example
char buffer[32];
size_t out_len;
const char *hex_string = "48656c6c6f20576f726c64"; // "Hello World" in hex
hex2bin(buffer, sizeof(buffer), hex_string, strlen(hex_string), &out_len);
// buffer now contains the binary representation of "Hello World"
Prototype
// Not applicable in JS
Prototype
# Not applicable in Python
Examples
// TODO C examples
// TODO JS examples
# TODO Python examples