I know usual conversion from oct_to_dec. Some smarter way?
A:
It would help to know WHY you want to do this via bit masking, because sometimes there are better ways to solve your problem globally, rather than this small request.
I have a feeling this is for homework, as Googling this problem found me forums with the same query as homework. If this is homework, then please tag it as homework as you did with the other question you asked recently.
I managed to find this site thanks to Google Perhaps it will help you understand...
void convertBase(int decimal) //Function that convert decimal to base of 8
{
const int mask1 = (7 << 3);
const int mask2 = (7 << 0);
firstDigit = (decimal & mask1) + '0';
secondDigit = (decimal & mask2) + '0';
printf("Octal Representation of Binary Number: %d%d\n", firstDigit, secondDigit);
}
Fuzz
2010-09-29 05:22:57
What do you mean by saying that the input is in decimal?
Sheldon L. Cooper
2010-09-29 05:25:51
good question Sheldon, you sure did bazinga me there :-)Decimal actually means a base 10 number.... so i assume this code is designed to work with a base 10 integer, as opposed to a numberical type named decimal.I haven't tested if this code actually works. I put as much effort in to this solution as the OP did with his homework. I just wanted to point out that there are things out there if you look :-)
Fuzz
2010-09-29 22:28:39
A:
This function reads an octal string and returns its numerical value.
int parse_octal(const char* s) {
int r = 0;
for ( ; *s; s++)
r = (r << 3) | (*s & 7);
return r;
}
It uses a bit mask for extracting the relevant bits of the ASCII value.
Sheldon L. Cooper
2010-09-29 06:53:54
In this context, that line is equivalent to: `r = r*8 + (*s - '0');`.
Sheldon L. Cooper
2010-09-29 07:20:13
Sheldon L. Cooper
2010-09-29 07:25:17