0

I know usual conversion from oct_to_dec. Some smarter way?

1
  • Could you explain what your restrictions are? How is the input represented? And most importantly, why do you have to use bit masks? Commented Sep 29, 2010 at 6:14

2 Answers 2

1

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); } 
Sign up to request clarification or add additional context in comments.

2 Comments

What do you mean by saying that the input is in decimal?
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 :-)
0

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.

2 Comments

In this context, that line is equivalent to: r = r*8 + (*s - '0');.
Shifting left three times is equivalent to multiplying by 2^3 = 8, which is the base. That's where the 3 comes from. 7 is the bit mask 111 (in binary). (*s & 7) extracts the 3 least significant bits of the ASCII value. For example, ('3' & 7) = 3 (note that '3' refers to the ASCII value and 3 to the number).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.