Binary array to printable hex string in C






1.24/5 (7 votes)
Tracing contents of a packet.
Introduction
This is generic function to trace out the contents of a packet (binary array).
Background
I needed to trace the contents of a packet and was looking for a piece of code to quickly trace out the contents of the packet. I wasn't able to find one on the net. So I wrote a simple function which prints out the binary blob in HEX string as you see it in WinDbg. Thought it would be a good idea to share out with others who might need it.
Using the code
Just include the trace function as it is. Instead of the AllocateMemory
function, which is my own alloc function, use any memory alloc you prefer. If your memory alloc function doesn't initialize the contents of the memory block returned, it would be a good idea to initialize it to 0 (mine initialises to 0). Instead of printf
, you can substitute it with any other trace function which your app might be using. Most of the apps dealing with network packets don't have a console to print to; rather they spew the data on to a debugger or have some kind of tracing.
///function to trace out a byte arr
DWORD TraceOut(BYTE* pConfigOut,DWORD dwSizeOfConfigOut)
{
DWORD retCode = 0;
DWORD dwSizeOfArr = (2 * dwSizeOfConfigOut) + 1;
CHAR* pszCharArr = NULL;
DWORD i = 0;
retCode = AllocateMemory(dwSizeOfArr, (PVOID*)&pszCharArr);
if (retCode != ERROR_SUCCESS)
{
goto cleanUp;
}
DWORD j =0;
for(i=0; i<dwSizeOfConfigOut ; i++)
{
char ch = pConfigOut[i];
char ch0 = (ch>>4) & 0x0F;
char ch1 = ch & 0x0F;
if((0<= ch0) && (ch0 <= 9))
{
pszCharArr[j] = '0' + ch0;
}
else
{
pszCharArr[j] = 'A' + (ch0 - 10);
}
j++;
if((0<= ch1) && (ch1 <= 9))
{
pszCharArr[j] = '0' + ch1;
}
else
{
pszCharArr[j] = 'A' + (ch1 - 10);
}
j++;
}
pszCharArr[j] = '\0';
printf("Binary array is %s", pszCharArr);
cleanUp:
return retCode;
}
Points of Interest
So if the binary blob is like this in (bits):
0000 1111 1111 1111 1110 1100 0000 0000 0000 0001
which in hex string would be:
0F FF EC 00 01
and you want to trace it out as it is.... you can read one character at a time from the binary blob and store it in a char
variable. Then extract out the left most four bits which represent one symbol of HEX, and then extract the right most four bits which represent the other HEX symbol.