0x20 and such


 
Thread Tools Search this Thread
Top Forums Programming 0x20 and such
# 8  
Old 06-26-2007
Quote:
Originally Posted by Octal
...trying to see what they do to diffrent characters
Forget about characters, this is dealing with bits, bytes and words.

Try this as a tutorial - write a few functions to print numbers out in different bases (binary, octal and hexidecimal) without using any division or multiplication.

eg

void print_in_hex(long);
void print_in_octal(long);
void print_in_binary(long);
# 9  
Old 06-26-2007
Code:
#include <stdio.h>

#define BITS_PER_BYTE 8

void hex(long);
void octel(long);
void binary(long);

main()
{
        long n;

        while (scanf("%ld", &n)) {
                hex(n);
                octel(n);
                binary(n);
        }
}

void hex(long n)
{
        printf("  %x\n", n);
}
void octel(long n)
{
        printf("  %o\n", n);
}
void binary(long n)
{
        int count = BITS_PER_BYTE;

        printf("  ");
        while (count--) {
                printf("%d", (n & 128) ? 1 : 0);

                n <<= 1;
        }
        printf("\n");
}

I put two spaces before the output so it's cleaner to read the outcome.
# 10  
Old 06-26-2007
Um, yes, well done, now do it without using printf/sprintf formatting.
Login or Register to Ask a Question

Previous Thread | Next Thread
Login or Register to Ask a Question