Convert HEX string to BYTE array, bug.

Find the bug in the following code and win a prize.
Its obvious once you find it. CSharp programmers are asked not to mock c++ in this thread.


#include "stdafx.h"
#include <string.h>
#include <stdio.h>

#define USHORT	unsigned short
#define BYTE	unsigned char 

USHORT ConvertHexToBytes(
		/* IN  */ char * hex,
		/* IN  */ const USHORT hex_length,
		/* OUT */ BYTE * buffer,
		/* OUT */ const USHORT buffer_length,
		/* IN  */ const char * delemnator = ":" )
{
	if( hex	== NULL || hex_length <= 0 ||
		buffer == NULL || buffer_length <= 0 )
	{
		return 0;
	}

	char *next_token = NULL;
	USHORT iOffset = 0 ;
	char *p = strtok_s(hex, delemnator, &next_token);
	while (p) {
		if( 1 != sscanf_s( p, "%02X", &buffer[ iOffset ] ) ) {
			break;
		}
		iOffset++;
		if( iOffset >= buffer_length ) {
			break; // No more room.
		}
		p = strtok_s(NULL, delemnator, &next_token);
	}
	return iOffset ;
}

2 Comments to Convert HEX string to BYTE array, bug.

  1. November 3, 2009 at 11:54 am | Permalink

    The bug is that you’re using C++

    That whole massive procedure is this in C#:
    HexEncoding.GetBytes(hexString, out discarded);

    C# RULES, C++ DROOLS!!!

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>