Just remember that a number itself is just an abstract mathematical object. The digits you see on a screen are a representational convention adopted to express numbers as a string of "symbols" (digits).
Here's a toy program (for simplicity) that print the digits of an integer in reverse:
Normally of course we would print them in the "proper order" as dictated by the convention of the base-10 representation, which is sums of powers of ten, largest powers first. (eg: 561 = (5) * 10 ^ 2 + (6) * 10^1 + (1) * 10^0). I leave it up as an exercise in case you want to give it a go for yourself.
Anyway a string of ASCII characters is really just a sequence of 8-bit numbers, so we can extend it to that as well.
Here's a toy program (for simplicity) that print the digits of an integer in reverse:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void integer_print_reverse(unsigned integer, const char* digits) {
unsigned base = strlen(digits);
do {
/*
Extract next digit and print
*/
unsigned index = integer % base;
putchar(digits[index]);
/*
Remove digit
*/
integer /= base;
} while (integer != 0);
putchar('\n');
}
void process(unsigned value) {
printf(" Value: %u\n", value);
puts("- Reversed -");
printf(" Decimal: ");
integer_print_reverse(value, "0123456789");
printf(" Hexadecimal: ");
integer_print_reverse(value, "0123456789ABCDEF");
printf(" Octal: ");
integer_print_reverse(value, "01234567");
printf(" Binary: ");
integer_print_reverse(value, "01");
}
int main(int argc, char** argv) {
if (argc == 1)
process(561);
else
for (;;) {
char* arg = *(++argv);
if (arg == NULL)
break;
process(atoi(arg));
}
}
Anyway a string of ASCII characters is really just a sequence of 8-bit numbers, so we can extend it to that as well.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void integer_print_reverse(unsigned integer, const char* digits) {
unsigned base = strlen(digits);
do {
/*
Extract next digit and print
*/
unsigned index = integer % base;
putchar(digits[index]);
/*
Remove digit
*/
integer /= base;
} while (integer != 0);
putchar('\n');
}
void process(const char* ascii) {
const char* hexadecimal = "0123456789ABCDEF";
size_t length = strlen(ascii);
puts(ascii);
puts("- Bytes in sequence (but digits reversed) in hexadecimal -");
for (size_t index = 0; index < length; ++index)
integer_print_reverse(ascii[index], hexadecimal);
}
int main(int argc, char** argv) {
if (argc == 1)
process("Hello World!");
else
for (;;) {
char* arg = *(++argv);
if (arg == NULL)
break;
process(arg);
}
}