Binary numbers do take a bit of getting used to, but it's not too bad once one figures out what's going on. This is not scientific by any means.
Start with 1 byte or 8 bits.
1 means a bit is set (on)
0 means a bit is not set (off)
bits 0-7
bit 0 = 1..... 2^0
bit 1 = 2..... 2^1
bit 2 = 4..... 2^2
bit 3 = 8..... 2^3
bit 4 = 16.... 2^4
bit 5 = 32.... 2^5
bit 6 = 64.... 2^6
bit 7 = 128.. 2^7
A bit pattern is read from right to left, so you must remember to fill in all missing left side bits with zeros (as you become familiar with the concept, you won't need to do that.)
1101 read right to left is
bit 0 set = 1
bit 1 not set = 0
bit 2 set = 1
bit 3 set = 1
the full eight bits
00001101b
look back at the bits 0-7 and add the set bits together. You get 13 dec. The 7th bit is a sign bit.
As far as a proggie, that isn't too hard either provided that you keep in mind my example is very basic.
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
int oneByte[8] = { 1, 2, 4, 8, 16, 32, 64, 128 };
char binary[15]; /* 8 bits + '\0' + overflow margin */
char buff[9];
char *SB; /* sign bit */
int i, j, decimal;
printf("Enter a binary string up to (8 bits): ");
gets(binary);
if(strlen(binary) > 8)
{
printf("\n\nInput string greater than eight bits");
return -1;
}
if(binary[0] == '\0')
{
printf("\n\nThere is nothing to do.");
return 0; /* not really an error */
}
j=0;
/* reverse string */
for(i=strlen(binary)-1; i >= 0; i--)
buff[j++] = binary[i];
/* terminate the reversed string */
buff[j] = '\0';
decimal = 0;
for(i=0; buff[i] != '\0'; i++)
{
/* use the switch to find out if the data
is good */
switch(buff[i])
{
case '0': break;
case '1': decimal += oneByte[i]; break;
case '\0': break;
default :
printf("\n\nInvalid entry => %c <= detected in input", buff[i]);
return -1;
break;
};
}
if(strlen(buff) == 8 && buff[7] == '1')
SB = "(unsigned)";
else
SB = "(signed)";
printf("\n\n%sb is %d dec %s", binary, decimal, SB);
return 0;
}
I *think* that will do... technically correct or not there ya go. Good luck.