Mail Archives: djgpp/2000/10/26/02:00:17
On Wed, 25 Oct 2000 21:13:13 GMT, bothersome AT mindspring DOT com (Nunya Bidny) wrote:
>
>Hi, I've started working on a small project that I want to do in C just to help
>me learn the constructs of the language. I'm in need of a couple of basic
>building blocks to use in the rest of the program. Here is what I need:
>I know there probably is an easy solution. I'm going to hit the books tonight
>to try to build my own routing, but I thought the good folks of the internet
>could probably build me a much more elegant looking one. This (full) project
>will probably be placed onto the internet for other people to see and study.
>Just for it's teaching qualities.
>This is not a home-work project... I'm 35 and just dabbling in this language.
>My email address is correct... so if you don't want everyone to see your code
>you can email if you want. But, I thought we were all here to learn.
Looks kinda funny to reply to my own message but... here goes :)
OK this is what I've come up with so far:
#include <stdio.h>
main(void) {
int x;
static unsigned char y[33];
x = 42;
printf(" %s ", Int2Bin(x, &y));
/* someone tell my why that worked!!! */
strcpy(y, "1011101011");
printf(" %d \n", Bin2Int(y));
}
int Int2Bin(int x, char *y) {
int i;
y += 32; *y-- = 0;
for (i = 0; i < 32; i++) {
*y-- = 48 + (x & 1);
x >>= 1;
}
}
int Bin2Int(char *x) {
int i;
i = 0;
do {
i <<= 1;
i += 1 & (*x++ == 49);
} while (*x != 0);
return i;
}
I've discovered it would make other stuff a lot easier if all my returned 1's
and 0's were all the same length (like 32 of em).
- Raw text -