diff mbox

[kvm-unit-tests,15/32] x86: binstr utility function

Message ID 20170421005004.137260-16-dmatlack@google.com (mailing list archive)
State New, archived
Headers show

Commit Message

David Matlack April 21, 2017, 12:49 a.m. UTC
From: Peter Feiner <pfeiner@google.com>

Signed-off-by: Peter Feiner <pfeiner@google.com>
Signed-off-by: David Matlack <dmatlack@google.com>
---
 lib/libcflat.h |  7 +++++++
 lib/printf.c   | 30 ++++++++++++++++++++++++++++++
 2 files changed, 37 insertions(+)
diff mbox

Patch

diff --git a/lib/libcflat.h b/lib/libcflat.h
index 248fd023626e..1d2eba980e1a 100644
--- a/lib/libcflat.h
+++ b/lib/libcflat.h
@@ -131,4 +131,11 @@  static inline bool is_power_of_2(unsigned long n)
 	return n && !(n & (n - 1));
 }
 
+/*
+ * One byte per bit, a ' between each group of 4 bits, and a null terminator.
+ */
+#define BINSTR_SZ (sizeof(unsigned long) * 8 + sizeof(unsigned long) * 2)
+void binstr(unsigned long x, char out[BINSTR_SZ]);
+void print_binstr(unsigned long x);
+
 #endif
diff --git a/lib/printf.c b/lib/printf.c
index 2aec59aa6d6d..cecbeadc4440 100644
--- a/lib/printf.c
+++ b/lib/printf.c
@@ -259,3 +259,33 @@  int printf(const char *fmt, ...)
     puts(buf);
     return r;
 }
+
+void binstr(unsigned long x, char out[BINSTR_SZ])
+{
+	int i;
+	char *c;
+	int n;
+
+	n = sizeof(unsigned long) * 8;
+	i = 0;
+	c = &out[0];
+	for (;;) {
+		*c++ = (x & (1ul << (n - i - 1))) ? '1' : '0';
+		i++;
+
+		if (i == n) {
+			*c = '\0';
+			break;
+		}
+		if (i % 4 == 0)
+			*c++ = '\'';
+	}
+	assert(c + 1 - &out[0] == BINSTR_SZ);
+}
+
+void print_binstr(unsigned long x)
+{
+	char out[BINSTR_SZ];
+	binstr(x, out);
+	printf("%s", out);
+}