I'm working on a simple hex editing type program and I was wondering
if there was any way to display the actual 1's and 0's of binary to
the screen. For example if I had some character, 'a' for example,
could I print the binary data for it, 01100001? This is a function
I would really like to include, for educational purposes, so if
there is anyway to do it, I would be be very happy if someone would
tell me. Thanks.
Very basic. See the following:
#ifndef dispbase_h_
#define dispbase_h_
#include <string.h>
/* ============================================ */
/* Mask and convert digit to hex representation */
/* Output range is 0..9 and a..f only */
int tio_hexify(unsigned int value);
/* ========================================= */
/* convert number to string in various bases */
/* 2 <= base <= 16, controlled by hexify() */
/* Output string has ls digit first. */
void tio_basedisplay(unsigned long number, unsigned int base,
char * string, size_t maxlgh);
/* ======================= */
/* reverse string in place */
void tio_revstring(char * string);
#endif
#include "dispbase.h"
/* ============================================ */
/* Mask and convert digit to hex representation */
/* Output range is 0..9 and a..f only */
int tio_hexify(unsigned int value)
{
int result;
result = (value & 0x0f) + '0';
if (result > '9')
result = result + ('a' - '0' - 10);
return result;
} /* tio_hexify */
/* ========================================= */
/* convert number to string in various bases */
/* 2 <= base <= 16, controlled by hexify() */
/* Output string has ls digit first. */
void tio_basedisplay(unsigned long number, unsigned int base,
char * string, size_t maxlgh)
{
/* assert (string[maxlgh]) is valid storage */
if (!maxlgh) {
*string = '\0';
return;
}
else {
*string = tio_hexify(number % base);
if (!number) *string = '\0';
else {
tio_basedisplay(number / base, base,
&string[1], maxlgh - 1);
}
}
} /* tio_basedisplay */
/* ======================= */
/* reverse string in place */
void tio_revstring(char * string)
{
char * last, temp;
last = string + strlen(string); /* points to '\0' */
while (last-- > string) {
temp = *string; *string++ = *last; *last = temp;
}
} /* tio_revstring */