Skip to content

Instantly share code, notes, and snippets.

@th-yoo
Created January 24, 2017 06:18
Show Gist options
  • Save th-yoo/e25b3120c06143923a646bcbd345ea5a to your computer and use it in GitHub Desktop.
Save th-yoo/e25b3120c06143923a646bcbd345ea5a to your computer and use it in GitHub Desktop.
binary dumper functions

C

static void dumpbin( const void* beg, const void* end
		   , size_t stride)
{
	static const char n2a[]
	= { '0', '1', '2', '3', '4', '5', '6', '7'
	  , '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
	
	const unsigned char* cur = (const unsigned char*)beg;
	const size_t len = stride? stride*3 : 3;
	char line[len];
	char* d = line;
	char* const de = d + len -1;

	line[len-1] = 0;
	while (cur < (unsigned char*)end) {
		*d++ = n2a[*cur>>4];
		*d++ = n2a[*cur++&0xF];
		if (d < de) {
			*d++ = ' ';
		}
		else {
			puts(line);
			d = line;
		}

	}
	if (d != line) {
		*d = 0;
		puts(line);
	}
}

Java

public static void dumpbin(byte[] b, int stride) {

	final String n2a = "0123456789ABCDEF";
	StringBuffer sb = new StringBuffer();
	int nc = 0;
	for (byte c : b) {
		sb.append(n2a.charAt((c>>>4)&0xF));
		sb.append(n2a.charAt(c&0xF));
		if (++nc != stride) {
			sb.append(" ");
		}
		else {
			nc = 0;
			System.out.println(sb.toString());
			sb.setLength(0);
		}
	}
	if (sb.length() > 0) {
			System.out.println(sb.toString());
	}
}
@th-yoo
Copy link
Author

th-yoo commented Mar 30, 2022

static void dumpbin( const void* beg, const void* end
		   , size_t stride)
{
	static const char n2a[]
	= { '0', '1', '2', '3', '4', '5', '6', '7'
	  , '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
	
	const unsigned char* cur = (const unsigned char*)beg;
	const size_t hexlen = stride? stride*3 : 3;
	const size_t len = hexlen + stride + 1;
	char line[len];
	char* d = line;
	char* const de = d + hexlen -1;
	line[len-1] = 0;

	const char* s = (const char*)cur;
	while (cur < (unsigned char*)end) {
		*d++ = n2a[*cur>>4];
		*d++ = n2a[*cur++&0xF];
		if (d < de) {
			*d++ = ' ';
		}
		else {
			*d++ = '\t';
			for (size_t i=0; i<stride; ++i) {
				*d++ = isprint(*s)? *s : '.';
				++s;
			}
			puts(line);

			d = line;
			s = (const char*)cur;
		}

	}
	if (d != line) {
		while (d < de) *d++ = ' ';
		*d++ = '\t';
		while (s < (const char*)end) {
			*d++ = isprint(*s)? *s : '.';
			++s;
		}
		*d = 0;
		puts(line);
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment