NetBurner 3.5.6
PDF Version
Utilities

Macros

#define DB_TCPIP   (1)
 Debug output control flags for NetBurner system components.
 
#define DB_HTTP   (2)
 HTTP debug messages.
 
#define DB_ETHER   (4)
 Ethernet debug messages.
 
#define DB_RTOS   (8)
 RTOS debug messages.
 
#define DB_BUFFER   (16)
 Buffer debug messages.
 
#define DB_PPP   (32)
 PPP debug messages.
 
#define DB_AU   (64)
 Authentication debug messages.
 
#define DB_MAIL   (128)
 Mail debug messages.
 
#define DB_IP   (256)
 IP debug messages.
 
#define DB_TCPDATA   (512)
 TCP data debug messages.
 
#define DB_SSL   (1024)
 SSL debug messages.
 
#define DB_SNMP   (2048)
 SNMP debug messages.
 
#define DB_IPV6_ND   (4096)
 IPv6 Neighbor Discovery debug messages.
 
#define DB_IPV6_ICMP   (8192)
 IPv6 ICMP debug messages.
 
#define DB_IPV6_ROUTE   (16384)
 IPv6 routing debug messages.
 
#define DB_IPV6_FRAG   (32768)
 IPv6 fragmentation debug messages.
 
#define DB_IPV6_ERR   (65536)
 IPv6 error debug messages.
 

Functions

IPADDR AsciiToIp6 (const char *p)
 Convert an ASCII IPv6 string to an IP address.
 
void ShowCounters ()
 Dump all system counters to stdio.
 
void sShowCounters (char *buffer, int slen)
 Dump all system counters to a memory buffer.
 
void FdShowRingData (int fd, const uint8_t *ringBuf, uint32_t bufLen, uint32_t start, uint32_t end, const char *indent=NULL)
 Dump part of a ring buffer to file descriptor.
 
void ShowRingData (const uint8_t *ringBuf, uint32_t bufLen, uint32_t start, uint32_t end, const char *indent=NULL)
 Dump part of a ring buffer to stdio.
 
void FdShowData (int fd, const uint8_t *fromptr, uint16_t len)
 Dump a block of data to file descriptor and show in ASCII and hex.
 
void ShowData (const uint8_t *fromptr, uint16_t len)
 Dump a block of data to stdio and show in ASCII and hex.
 
void ShowMac (const MACADR *ma)
 Dump a MAC address to stdio.
 
void fdShowMac (int fd, const MACADR *ma)
 Dump a MAC address to file descriptor.
 
void ShowMac (const MACADR &ma)
 Dump a MAC address to stdio (reference version)
 
void snShowMac (char *buf, size_t maxlen, const MACADR *ma)
 Dump a MAC address to character buffer.
 
void snShowMac (char *buf, size_t maxlen, const MACADR &ma)
 Dump a MAC address to character buffer (reference version)
 
void MacToID (MACADR *ma, char *IDBuf)
 Write 6 character ID string based on unique portion of MAC.
 
void outbyte (char c)
 Write out a single, unbuffered byte to stdio.
 
void print (const char *str)
 Write out a zero-terminated, unbuffered string.
 
void putnum (int i)
 Write out a hexadecimal, unbuffered number to stdio.
 
void putbytenum (unsigned char c)
 Write out a hexadecimal, unbuffered byte to stdio.
 
IPADDR4 AsciiToIp4 (const char *p)
 Convert an ASCII IPv4 string to an IP address.
 
MACADR AsciiToMac (const char *p)
 Convert an ASCII MAC address string to a MAC address.
 
BOOL ValidIPv4 (const char *p)
 Validate if a string contains a valid IPv4 address.
 
void ShowIP4 (const IPADDR4 ia)
 Dump an IPv4 address in ASCII IP string format to stdio.
 
int snShowIP4 (char *buf, size_t maxlen, const IPADDR4 ia)
 Dump an IPv4 address in ASCII IP string format to character buffer.
 
void ShowIP6 (const IPADDR &ia)
 Dump an IPv6 address in ASCII IP string format to stdio.
 
int snShowIP6 (char *buf, size_t maxlen, const IPADDR &ia)
 Dump an IPv6 address in ASCII IP string format to character buffer.
 
uint32_t GetPreciseTime (void)
 Gets the time tick since system start at a higher resolution.
 
unsigned long long Get_msec ()
 Returns the number of milliseconds as a 64-bit value.
 
int kill (int pid, int sig)
 Send a signal to a process.
 
void _exit (int i)
 Terminate the calling process.
 
int _fini (void)
 Finalization function.
 
unsigned char * convertBinaryToHexAscii (unsigned char *fromBufferPtr, unsigned int fromByteCount, unsigned char *toBufferPtr, unsigned int toByteCount)
 Convert binary data to hexadecimal ASCII representation.
 
unsigned char * convertHexAsciiToBinary (unsigned char *fromBufferPtr, unsigned int fromByteCount, unsigned char *toBufferPtr, unsigned int toByteCount)
 Convert hexadecimal ASCII string to binary data.
 
const char * bufnstr (const char *search, const char *target, size_t len)
 Search for a C string in an arbitrary memory blob that may contain NULL chars.
 

Detailed Description

#include< utils.h>


Macro Definition Documentation

◆ DB_TCPIP

#define DB_TCPIP   (1)

#include <utils.h>

Debug output control flags for NetBurner system components.

These flags control diagnostic output from various NetBurner subsystems. Set the global DB_FLAGS variable to enable debug messages from specific components. Flags can be combined using bitwise OR to enable multiple debug outputs simultaneously.

Use requires the declaration of unsigned int DB_FLAGS = NB_SSL, usually in main.cpp. At least one flag or a value of 0 must be set in the DB_FLAGS declaration.

Note
Debug output should be disabled in production code as it adds overhead and can flood the console with messages.
#include <utils.h>
void UserMain(void *pd) {
init();
// Enable TCP/IP debug messages only
unsigned int DB_FLAGS = DB_TCPIP | DB_SSL;
// Now you'll see TCP/IP and SSL related debug output in the console
while (1) {
OSTimeDly(TICKS_PER_SECOND);
}
}
#define DB_SSL
SSL debug messages.
Definition utils.h:80
#define DB_TCPIP
Debug output control flags for NetBurner system components.
Definition utils.h:70
#define TICKS_PER_SECOND
System clock ticks per second.
Definition constants.h:49
void init()
System initialization. Ideally called at the beginning of all applications, since the easiest Recover...

TCP/IP debug messages

Function Documentation

◆ _exit()

void _exit ( int i)

#include <utils.h>

Terminate the calling process.

Parameters
iExit status

◆ _fini()

int _fini ( void )

#include <utils.h>

Finalization function.

Returns
Status code

◆ AsciiToIp4()

IPADDR4 AsciiToIp4 ( const char * p)

#include <utils.h>

Convert an ASCII IPv4 string to an IP address.

Parameters
pPointer to null-terminated ASCII IPv4 string
Returns
IPADDR4 object containing the converted IPv4 address

◆ AsciiToIp6()

IPADDR AsciiToIp6 ( const char * p)

#include <utils.h>

Convert an ASCII IPv6 string to an IP address.

Parameters
pPointer to null-terminated ASCII IPv6 string
Returns
IPADDR object containing the converted IPv6 address

◆ AsciiToMac()

MACADR AsciiToMac ( const char * p)

#include <utils.h>

Convert an ASCII MAC address string to a MAC address.

Parameters
pPointer to null-terminated ASCII MAC address string
Returns
MACADR object containing the converted MAC address

◆ bufnstr()

const char * bufnstr ( const char * search,
const char * target,
size_t len )

#include <utils.h>

Search for a C string in an arbitrary memory blob that may contain NULL chars.

Parameters
searchPointer to the buffer to search
targetThe C string being searched for
lenLength of the search buffer
Returns
Pointer to the start of the target string in the search buffer, or NULL if target not found

◆ convertBinaryToHexAscii()

unsigned char * convertBinaryToHexAscii ( unsigned char * fromBufferPtr,
unsigned int fromByteCount,
unsigned char * toBufferPtr,
unsigned int toByteCount )

#include <utils.h>

Convert binary data to hexadecimal ASCII representation.

Converts raw binary data into a hexadecimal ASCII string where each byte is represented by two hexadecimal characters (0-9, A-F). For example, the byte value 0xFF becomes the two-character string "FF".

This function is commonly used for:

  • Displaying binary data in human-readable format
  • Creating hexadecimal dumps of memory or packet contents
  • Encoding binary data for text-based protocols
  • Debugging network packets or cryptographic operations
Parameters
fromBufferPtrPointer to the source buffer containing binary data to convert
fromByteCountNumber of bytes to convert from the source buffer
toBufferPtrPointer to the destination buffer for hexadecimal ASCII output
toByteCountSize of the destination buffer in bytes
Returns
Pointer to the next free byte in the destination buffer after conversion. Returns NULL if the destination buffer is too small.
Note
The destination buffer must be at least (fromByteCount * 2) bytes to hold the complete hexadecimal representation, plus 1 byte if null-termination is desired.
The output is NOT automatically null-terminated. Add a null terminator manually if you need a C-string: ‘*result = ’\0';`
Uses uppercase hexadecimal characters (A-F) not lowercase (a-f)
If toByteCount < (fromByteCount * 2), conversion will stop when the destination buffer is full and return NULL to indicate buffer overflow
Warning
Always ensure the destination buffer is large enough to prevent buffer overflow: toByteCount >= (fromByteCount * 2)
This function does not add any separators (spaces, colons, etc.) between bytes

Expand for Example Usage

Examples

Example 1: Basic Binary to Hex Conversion
unsigned char binaryData[] = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; // "Hello"
unsigned char hexBuffer[20]; // Need at least 10 bytes (5 * 2)
unsigned char *nextPtr = convertBinaryToHexAscii(
binaryData,
sizeof(binaryData),
hexBuffer,
sizeof(hexBuffer)
);
if (nextPtr != NULL) {
*nextPtr = '\0'; // Null-terminate for printing
iprintf("Hex: %s\r\n", hexBuffer); // Output: "48656C6C6F"
}
unsigned char * convertBinaryToHexAscii(unsigned char *fromBufferPtr, unsigned int fromByteCount, unsigned char *toBufferPtr, unsigned int toByteCount)
Convert binary data to hexadecimal ASCII representation.
Example 2: Display MAC Address in Hex
void DisplayMACAddress(unsigned char *macAddr) {
unsigned char hexBuffer[13]; // 6 bytes * 2 = 12, plus null terminator
unsigned char *result = convertBinaryToHexAscii(
macAddr,
6, // MAC address is 6 bytes
hexBuffer,
sizeof(hexBuffer) - 1 // Leave room for null terminator
);
if (result != NULL) {
*result = '\0';
// Format with colons for readability
iprintf("MAC: %c%c:%c%c:%c%c:%c%c:%c%c:%c%c\r\n",
hexBuffer[0], hexBuffer[1], // First byte
hexBuffer[2], hexBuffer[3], // Second byte
hexBuffer[4], hexBuffer[5], // Third byte
hexBuffer[6], hexBuffer[7], // Fourth byte
hexBuffer[8], hexBuffer[9], // Fifth byte
hexBuffer[10], hexBuffer[11]); // Sixth byte
}
}
Example 3: Hex Dump of Network Packet
void HexDumpPacket(unsigned char *packet, unsigned int length) {
const int bytesPerLine = 16;
unsigned char hexBuffer[64]; // 16 bytes * 2 = 32, with extra space
iprintf("Packet hex dump (%u bytes):\r\n", length);
for (unsigned int offset = 0; offset < length; offset += bytesPerLine) {
unsigned int lineBytes = (length - offset < bytesPerLine) ?
(length - offset) : bytesPerLine;
// Convert this line to hex
unsigned char *result = convertBinaryToHexAscii(
packet + offset,
lineBytes,
hexBuffer,
sizeof(hexBuffer)
);
if (result != NULL) {
*result = '\0';
iprintf("%04X: %s\r\n", offset, hexBuffer);
}
}
}
Example 4: Convert Hash to Hex String
#include <md5.h>
void DisplayMD5Hash(const char *data, unsigned int length) {
unsigned char hash[16]; // MD5 produces 16 bytes
unsigned char hexHash[33]; // 16 * 2 = 32, plus null terminator
// Calculate MD5 hash (example function)
MD5_CTX ctx;
MD5Init(&ctx);
MD5Update(&ctx, (unsigned char *)data, length);
MD5Final(hash, &ctx);
// Convert to hex string
unsigned char *result = convertBinaryToHexAscii(
hash,
16,
hexHash,
sizeof(hexHash) - 1
);
if (result != NULL) {
*result = '\0';
iprintf("MD5: %s\r\n", hexHash);
}
}
Example 5: Error Handling for Buffer Overflow
bool ConvertToHexSafely(unsigned char *binary, unsigned int binLen,
char *hexStr, unsigned int hexLen) {
// Check if destination buffer is large enough
if (hexLen < (binLen * 2 + 1)) {
iprintf("ERROR: Hex buffer too small. Need %u bytes, have %u\r\n",
binLen * 2 + 1, hexLen);
return false;
}
unsigned char *result = convertBinaryToHexAscii(
binary,
binLen,
(unsigned char *)hexStr,
hexLen - 1 // Leave room for null terminator
);
if (result == NULL) {
iprintf("ERROR: Conversion failed\r\n");
return false;
}
*result = '\0';
return true;
}
// Usage
unsigned char data[] = {0xDE, 0xAD, 0xBE, 0xEF};
char hexStr[20];
if (ConvertToHexSafely(data, sizeof(data), hexStr, sizeof(hexStr))) {
iprintf("Success: %s\r\n", hexStr); // Output: "DEADBEEF"
}
Example 6: Encode Binary Data for HTTP/JSON
void SendBinaryDataAsJSON(int sock, unsigned char *data, unsigned int length) {
unsigned char hexBuffer[512];
// Check if data fits
if (length * 2 >= sizeof(hexBuffer)) {
iprintf("ERROR: Data too large for hex encoding\r\n");
return;
}
unsigned char *result = convertBinaryToHexAscii(
data,
length,
hexBuffer,
sizeof(hexBuffer) - 1
);
if (result != NULL) {
*result = '\0';
// Send as JSON
NBString json;
json.sprintf("{\"data\":\"%s\",\"length\":%u}", hexBuffer, length);
writestring(sock, "HTTP/1.1 200 OK\r\n");
writestring(sock, "Content-Type: application/json\r\n\r\n");
writestring(sock, json.c_str());
}
}
Lightweight alternative to C++ CString class.
Definition nbstring.h:118
const char * c_str() const
Method to pass a NBString as a constant char *.
int sprintf(const char *format,...)
sprintf to a string with formatting to a character array
int writestring(int fd, const char *str)
Write a null terminated ascii string to the stream associated with a file descriptor (fd)....
Example 7: Convert Serial Number to Hex String
void DisplayDeviceSerialNumber() {
unsigned char serialNum[16]; // Example: 16-byte serial number
unsigned char hexSerial[33]; // 16 * 2 = 32, plus null
// Get serial number from device (example function)
GetDeviceSerialNumber(serialNum, sizeof(serialNum));
unsigned char *result = convertBinaryToHexAscii(
serialNum,
sizeof(serialNum),
hexSerial,
sizeof(hexSerial) - 1
);
if (result != NULL) {
*result = '\0';
iprintf("Device Serial: %s\r\n", hexSerial);
}
}
Example 8: Format with Spaces Between Bytes
void ConvertToHexWithSpaces(unsigned char *binary, unsigned int length) {
// Need 2 chars per byte + 1 space per byte (except last)
unsigned char hexBuffer[256];
unsigned char *ptr = hexBuffer;
for (unsigned int i = 0; i < length; i++) {
// Convert one byte at a time
unsigned char *result = convertBinaryToHexAscii(
&binary[i],
1, // One byte
ptr,
3 // Two hex chars + space
);
if (result == NULL) break;
ptr = result;
// Add space between bytes (except after last byte)
if (i < length - 1) {
*ptr++ = ' ';
}
}
*ptr = '\0';
iprintf("Hex: %s\r\n", hexBuffer);
// Example output: "48 65 6C 6C 6F"
}


See also
convertHexAsciitoBinary() - Reverse operation: hex ASCII to binary

◆ convertHexAsciiToBinary()

unsigned char * convertHexAsciiToBinary ( unsigned char * fromBufferPtr,
unsigned int fromByteCount,
unsigned char * toBufferPtr,
unsigned int toByteCount )

#include <utils.h>

Convert hexadecimal ASCII string to binary data.

Converts a hexadecimal ASCII string (where each pair of characters represents one byte) into raw binary data. This is the reverse operation of convertBinaryToHexAscii(). For example, the string "FF" becomes the byte value 0xFF, and "48656C6C6F" becomes the five bytes {0x48, 0x65, 0x6C, 0x6C, 0x6F} which represents "Hello".

This function is commonly used for:

  • Parsing hexadecimal data from configuration files or user input
  • Decoding hex-encoded network protocols
  • Converting hex strings from web forms or JSON
  • Processing hexadecimal MAC addresses, hashes, or serial numbers
Parameters
fromBufferPtrPointer to the source buffer containing hexadecimal ASCII string
fromByteCountNumber of ASCII characters to convert (must be even for complete bytes)
toBufferPtrPointer to the destination buffer for binary output
toByteCountSize of the destination buffer in bytes
Returns
Pointer to the next free byte in the destination buffer after conversion. Returns NULL if conversion fails (invalid hex characters, odd length, or buffer too small).
Note
The source string should contain only valid hexadecimal characters (0-9, A-F, a-f)
fromByteCount should be even (two hex chars = one binary byte). If odd, the last character may be ignored or cause an error.
The destination buffer must be at least (fromByteCount / 2) bytes in size
Both uppercase (A-F) and lowercase (a-f) hex characters are accepted
The source string does NOT need to be null-terminated; conversion uses fromByteCount
Warning
If fromByteCount is odd, behavior depends on implementation - may ignore last char or return NULL. Always provide an even number of hex characters.
Invalid hex characters (G-Z, special chars, etc.) will cause conversion to fail
Always ensure the destination buffer is large enough: toByteCount >= (fromByteCount / 2)

Expand for Example Usage

Examples

Example 1: Basic Hex String to Binary Conversion
const char *hexString = "48656C6C6F"; // "Hello" in hex
unsigned char binaryData[10];
unsigned char *result = convertHexAsciiToBinary(
(unsigned char *)hexString,
strlen(hexString), // 10 characters = 5 bytes
binaryData,
sizeof(binaryData)
);
if (result != NULL) {
unsigned int bytesConverted = result - binaryData;
iprintf("Converted %u bytes\r\n", bytesConverted);
iprintf("Text: %.*s\r\n", bytesConverted, binaryData); // Output: "Hello"
} else {
iprintf("Conversion failed\r\n");
}
unsigned char * convertHexAsciiToBinary(unsigned char *fromBufferPtr, unsigned int fromByteCount, unsigned char *toBufferPtr, unsigned int toByteCount)
Convert hexadecimal ASCII string to binary data.
Example 2: Parse MAC Address from Hex String
bool ParseMACAddress(const char *hexMAC, unsigned char *macBytes) {
// Remove colons/dashes if present, or use hex string directly
// Example input: "001122334455" (12 hex chars = 6 bytes)
if (strlen(hexMAC) != 12) {
iprintf("ERROR: MAC address must be 12 hex characters\r\n");
return false;
}
unsigned char *result = convertHexAsciiToBinary(
(unsigned char *)hexMAC,
12,
macBytes,
6
);
if (result == NULL) {
iprintf("ERROR: Invalid hex characters in MAC address\r\n");
return false;
}
iprintf("MAC: %02X:%02X:%02X:%02X:%02X:%02X\r\n",
macBytes[0], macBytes[1], macBytes[2],
macBytes[3], macBytes[4], macBytes[5]);
return true;
}
// Usage
unsigned char mac[6];
if (ParseMACAddress("001122AABBCC", mac)) {
// Use MAC address
}
Example 3: Decode Hex Data from HTTP POST
void HandleHexDataPost(int sock, const char *hexData) {
unsigned char binaryData[256];
unsigned int hexLen = strlen(hexData);
// Validate hex string length
if (hexLen % 2 != 0) {
writestring(sock, "HTTP/1.1 400 Bad Request\r\n\r\n");
writestring(sock, "Hex string must have even length");
return;
}
if (hexLen / 2 > sizeof(binaryData)) {
writestring(sock, "HTTP/1.1 413 Payload Too Large\r\n\r\n");
return;
}
// Convert hex to binary
unsigned char *result = convertHexAsciiToBinary(
(unsigned char *)hexData,
hexLen,
binaryData,
sizeof(binaryData)
);
if (result == NULL) {
writestring(sock, "HTTP/1.1 400 Bad Request\r\n\r\n");
writestring(sock, "Invalid hex characters");
return;
}
unsigned int byteCount = result - binaryData;
// Process binary data
ProcessBinaryData(binaryData, byteCount);
writestring(sock, "HTTP/1.1 200 OK\r\n\r\n");
writestring(sock, "Data processed successfully");
}
Example 4: Parse Configuration Value in Hex
bool LoadEncryptionKey(const char *hexKey, unsigned char *keyBytes,
unsigned int expectedKeySize) {
unsigned int hexLen = strlen(hexKey);
// Check if hex string represents correct key size
if (hexLen != expectedKeySize * 2) {
iprintf("ERROR: Key must be %u bytes (%u hex chars)\r\n",
expectedKeySize, expectedKeySize * 2);
return false;
}
unsigned char *result = convertHexAsciiToBinary(
(unsigned char *)hexKey,
hexLen,
keyBytes,
expectedKeySize
);
if (result == NULL) {
iprintf("ERROR: Invalid hex characters in encryption key\r\n");
return false;
}
iprintf("Encryption key loaded successfully\r\n");
return true;
}
// Usage: Load 128-bit (16 byte) AES key
unsigned char aesKey[16];
if (LoadEncryptionKey("0123456789ABCDEF0123456789ABCDEF", aesKey, 16)) {
// Use key for encryption
}
Example 5: Convert JSON Hex Field to Binary
#include <json_lexer.h>
bool ParseHexFromJSON(const char *jsonStr, unsigned char *output,
unsigned int maxOutputSize) {
ParsedJsonDataSet json(jsonStr);
// Get hex string from JSON field
const char *hexValue = json["data"].GetStr();
if (hexValue == NULL) {
iprintf("ERROR: 'data' field not found in JSON\r\n");
return false;
}
unsigned int hexLen = strlen(hexValue);
if (hexLen / 2 > maxOutputSize) {
iprintf("ERROR: Hex data too large for buffer\r\n");
return false;
}
unsigned char *result = convertHexAsciiToBinary(
(unsigned char *)hexValue,
hexLen,
output,
maxOutputSize
);
return (result != NULL);
}
// Usage with JSON: {"data":"DEADBEEF"}
unsigned char binaryData[256];
if (ParseHexFromJSON(jsonString, binaryData, sizeof(binaryData))) {
// Process binary data
}
A class to create, read, and modify a JSON object.
Definition json_lexer.h:535
Example 6: Validate and Convert Hex String
bool IsValidHexString(const char *str) {
// Check for even length
unsigned int len = strlen(str);
if (len % 2 != 0) return false;
// Check all characters are valid hex
for (unsigned int i = 0; i < len; i++) {
char c = str[i];
if (!((c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'F') ||
(c >= 'a' && c <= 'f'))) {
return false;
}
}
return true;
}
bool SafeHexToBinary(const char *hexStr, unsigned char *binary,
unsigned int binarySize) {
// Pre-validate before conversion
if (!IsValidHexString(hexStr)) {
iprintf("ERROR: Invalid hex string format\r\n");
return false;
}
unsigned int hexLen = strlen(hexStr);
if (hexLen / 2 > binarySize) {
iprintf("ERROR: Output buffer too small\r\n");
return false;
}
unsigned char *result = convertHexAsciiToBinary(
(unsigned char *)hexStr,
hexLen,
binary,
binarySize
);
return (result != NULL);
}
Example 7: Round-Trip Conversion Test
void TestHexConversions() {
// Original binary data
unsigned char original[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE};
// Convert to hex
unsigned char hexBuffer[20];
unsigned char *hexResult = convertBinaryToHexAscii(
original,
sizeof(original),
hexBuffer,
sizeof(hexBuffer) - 1
);
if (hexResult == NULL) {
iprintf("Hex conversion failed\r\n");
return;
}
*hexResult = '\0';
iprintf("Hex: %s\r\n", hexBuffer); // "DEADBEEFCAFE"
// Convert back to binary
unsigned char restored[10];
unsigned char *binResult = convertHexAsciiToBinary(
hexBuffer,
strlen((char *)hexBuffer),
restored,
sizeof(restored)
);
if (binResult == NULL) {
iprintf("Binary conversion failed\r\n");
return;
}
// Verify round-trip
if (memcmp(original, restored, sizeof(original)) == 0) {
iprintf("Round-trip conversion successful!\r\n");
} else {
iprintf("ERROR: Round-trip conversion mismatch\r\n");
}
}
Example 8: Parse Hex String with Mixed Case
void DemoMixedCaseHex() {
// Both uppercase and lowercase hex chars are valid
const char *mixedHex = "DeAdBeEf";
unsigned char binary[4];
unsigned char *result = convertHexAsciiToBinary(
(unsigned char *)mixedHex,
strlen(mixedHex),
binary,
sizeof(binary)
);
if (result != NULL) {
iprintf("Converted: ");
for (int i = 0; i < 4; i++) {
iprintf("%02X ", binary[i]);
}
iprintf("\r\n"); // Output: "DE AD BE EF"
}
}
Example 9: Parse Serial Number from User Input
bool SetDeviceSerialNumber(const char *hexSerial) {
const unsigned int SERIAL_SIZE = 16; // 16 bytes = 128 bits
unsigned char serialBytes[SERIAL_SIZE];
// Validate input length
if (strlen(hexSerial) != SERIAL_SIZE * 2) {
iprintf("ERROR: Serial number must be %u hex characters\r\n",
SERIAL_SIZE * 2);
return false;
}
// Convert to binary
unsigned char *result = convertHexAsciiToBinary(
(unsigned char *)hexSerial,
SERIAL_SIZE * 2,
serialBytes,
SERIAL_SIZE
);
if (result == NULL) {
iprintf("ERROR: Invalid hex characters in serial number\r\n");
return false;
}
// Store serial number (example function)
StoreSerialNumberToFlash(serialBytes, SERIAL_SIZE);
iprintf("Serial number set successfully\r\n");
return true;
}


See also
convertBinaryToHexAscii() - Reverse operation: binary to hex ASCII

◆ FdShowData()

void FdShowData ( int fd,
const uint8_t * fromptr,
uint16_t len )

#include <utils.h>

Dump a block of data to file descriptor and show in ASCII and hex.

Parameters
fdFile descriptor to write to
fromptrPointer to data to display
lenNumber of bytes to display

◆ fdShowMac()

void fdShowMac ( int fd,
const MACADR * ma )

#include <utils.h>

Dump a MAC address to file descriptor.

Parameters
fdFile descriptor to write to
maPointer to MACADR structure to display

◆ FdShowRingData()

void FdShowRingData ( int fd,
const uint8_t * ringBuf,
uint32_t bufLen,
uint32_t start,
uint32_t end,
const char * indent = NULL )

#include <utils.h>

Dump part of a ring buffer to file descriptor.

Parameters
fdFile descriptor to write to
ringBufPointer to ring buffer data
bufLenTotal length of ring buffer
startStart offset in ring buffer
endEnd offset in ring buffer
indentOptional indentation string for formatting (can be NULL)

◆ Get_msec()

unsigned long long Get_msec ( )

#include <utils.h>

Returns the number of milliseconds as a 64-bit value.

Return values
Numberof milliseconds

◆ GetPreciseTime()

uint32_t GetPreciseTime ( void )
extern

#include <utils.h>

Gets the time tick since system start at a higher resolution.

Resolution depends on the platform: 0.868-us for MOD5234/70, and 1.929-us for MOD5282

Returns
High resolution time tick as uint32_t

◆ kill()

int kill ( int pid,
int sig )

#include <utils.h>

Send a signal to a process.

Parameters
pidProcess ID
sigSignal number
Returns
0 on success, -1 on error

◆ MacToID()

void MacToID ( MACADR * ma,
char * IDBuf )

#include <utils.h>

Write 6 character ID string based on unique portion of MAC.

Parameters
maPointer to MACADR structure
IDBufBuffer to write 6-character ID string to (must be at least 7 bytes for null terminator)

◆ outbyte()

void outbyte ( char c)

#include <utils.h>

Write out a single, unbuffered byte to stdio.

Parameters
cCharacter to output

◆ print()

void print ( const char * str)

#include <utils.h>

Write out a zero-terminated, unbuffered string.

Parameters
strPointer to null-terminated string to output

◆ putbytenum()

void putbytenum ( unsigned char c)

#include <utils.h>

Write out a hexadecimal, unbuffered byte to stdio.

Parameters
cByte value to output in hexadecimal format

◆ putnum()

void putnum ( int i)

#include <utils.h>

Write out a hexadecimal, unbuffered number to stdio.

Parameters
iInteger value to output in hexadecimal format

◆ ShowData()

void ShowData ( const uint8_t * fromptr,
uint16_t len )

#include <utils.h>

Dump a block of data to stdio and show in ASCII and hex.

Parameters
fromptrPointer to data to display
lenNumber of bytes to display

◆ ShowIP4()

void ShowIP4 ( const IPADDR4 ia)

#include <utils.h>

Dump an IPv4 address in ASCII IP string format to stdio.

Parameters
iaIPv4 address to display

◆ ShowIP6()

void ShowIP6 ( const IPADDR & ia)
inline

#include <utils.h>

Dump an IPv6 address in ASCII IP string format to stdio.

Parameters
iaIPv6 address to display

◆ ShowMac() [1/2]

void ShowMac ( const MACADR & ma)
inline

#include <utils.h>

Dump a MAC address to stdio (reference version)

Parameters
maReference to MACADR structure to display

◆ ShowMac() [2/2]

void ShowMac ( const MACADR * ma)

#include <utils.h>

Dump a MAC address to stdio.

Parameters
maPointer to MACADR structure to display

◆ ShowRingData()

void ShowRingData ( const uint8_t * ringBuf,
uint32_t bufLen,
uint32_t start,
uint32_t end,
const char * indent = NULL )

#include <utils.h>

Dump part of a ring buffer to stdio.

Parameters
ringBufPointer to ring buffer data
bufLenTotal length of ring buffer
startStart offset in ring buffer
endEnd offset in ring buffer
indentOptional indentation string for formatting (can be NULL)

◆ snShowIP4()

int snShowIP4 ( char * buf,
size_t maxlen,
const IPADDR4 ia )

#include <utils.h>

Dump an IPv4 address in ASCII IP string format to character buffer.

Parameters
bufBuffer to write IP address string to
maxlenMaximum length of buffer
iaIPv4 address to convert
Returns
Number of characters written to buffer

◆ snShowIP6()

int snShowIP6 ( char * buf,
size_t maxlen,
const IPADDR & ia )
inline

#include <utils.h>

Dump an IPv6 address in ASCII IP string format to character buffer.

Parameters
bufBuffer to write IP address string to
maxlenMaximum length of buffer
iaIPv6 address to convert
Returns
Number of characters written to buffer

◆ snShowMac() [1/2]

void snShowMac ( char * buf,
size_t maxlen,
const MACADR & ma )
inline

#include <utils.h>

Dump a MAC address to character buffer (reference version)

Parameters
bufBuffer to write MAC address string to
maxlenMaximum length of buffer
maReference to MACADR structure to convert

◆ snShowMac() [2/2]

void snShowMac ( char * buf,
size_t maxlen,
const MACADR * ma )

#include <utils.h>

Dump a MAC address to character buffer.

Parameters
bufBuffer to write MAC address string to
maxlenMaximum length of buffer
maPointer to MACADR structure to convert

◆ sShowCounters()

void sShowCounters ( char * buffer,
int slen )

#include <utils.h>

Dump all system counters to a memory buffer.

Parameters
bufferPointer to buffer to store counter information
slenSize of the buffer in bytes

◆ ValidIPv4()

BOOL ValidIPv4 ( const char * p)

#include <utils.h>

Validate if a string contains a valid IPv4 address.

Parameters
pPointer to null-terminated string to validate
Returns
TRUE if string contains valid IPv4 address, FALSE otherwise