乐闻世界logo
搜索文章和话题

How do you convert a byte array to a hexadecimal string in C?

1个答案

1

In C programming, converting a byte array to a hexadecimal string is a common operation, especially when dealing with network communication or binary data formats. Here, I will detail the conversion process and provide a specific example to illustrate how to implement it.

Steps:

  1. Prepare the Character Array: To perform the conversion, we need to prepare a character array to store the converted hexadecimal string. In hexadecimal, each byte can be represented as two characters (e.g., 0xFF), so the target string length is twice the source byte data length, plus one additional character for the null terminator \'\0\'.

  2. Conversion Process: Iterate through the byte array, converting each byte to its corresponding two hexadecimal characters. This can be achieved using a lookup table (character array) that contains the mappings for '0' to '9' and 'A' to 'F', or by directly formatting the output using the sprintf function.

  3. Store Results: Store the formatted characters in the pre-allocated character array, ensuring the string ends with the null terminator \'\0\'.

Example Code:

c
#include <stdio.h> void bytesToHexStr(const unsigned char *bytes, int bytesLen, char *hexStr) { int i = 0; for (; i < bytesLen; ++i) { // Convert each byte's high 4 bits and low 4 bits to hexadecimal characters sprintf(&hexStr[i * 2], "%02X", bytes[i]); } hexStr[i * 2] = '\0'; // Add null terminator } int main() { unsigned char bytes[] = {0x12, 0xAB, 0x34, 0xCD}; // Example byte array int bytesLen = sizeof(bytes) / sizeof(bytes[0]); char hexStr[bytesLen * 2 + 1]; // Allocate sufficient space for the hexadecimal string bytesToHexStr(bytes, bytesLen, hexStr); printf("Hexadecimal string: %s\n", hexStr); return 0; }

Explanation:

In this example, the bytesToHexStr function takes three parameters: the source byte array bytes, the array length bytesLen, and the string hexStr to store the result. We iterate through the byte array and use sprintf to format each byte into two hexadecimal characters. This method is concise and easy to understand.

2024年8月22日 16:19 回复

你的答案