1
votes

I am not looking for any kind of codes here. I will write the code by myself, once I understand the logic, how to convert a decimal number into octal using bitwise operators. I know it would be much easier to use multiplication/division, but I want to use bitwise operators instead.

Greatly appreciate it if someone could help me out with the logic. (No multiplications or divisions)

1
If you're going for bitwise operators, it's easier to think of the numbers in binary as opposed to decimal - in which case octals can be represented by 3 bits, N&7 (00000111) will get your least significant octal, and from there you can right-shift by 3 and AND 7 so on and so forth - Enfyve

1 Answers

1
votes

You are looking to convert from base 10 to base 8. The easiest way to accomplish this is to think in binary, base 2. Lets assume you enter a number to be stored by a variable. Most likely you are entering this number in Base 10, however when you try to use bitwise operators on the stored value it will treat the number as if it was base 2. This image explains converting from base 2 to base 10. This image explains converting from base 2 to base 10.

Notice the first three bits, they are equivalent to 1, 2, and 4, including 0 this means these first three digits can represent 8 different numbers. In other words, every three digits in binary represents one digit in octal. This means that the first three from the decimal point are your first octal digit, the second three are the second and so on and so forth. As an example 71 in binary is 1000111 (or 64+8+4+2+1) splitting this into sections of three gives 111 in binary or 7 for the ones place, 000 in binary or 0 for the tens place, and 001 in binary or 1 in decimal for the hundreds place of our octal number. As such 71 in decimal would equal 107.

Codewise you'll need to use bitwise operators to create a temporary value that is equal to the first 3 digits of the number. The value of this temp value will be in the place corresponding to how many times you have run the operation (first time singles, second time tens ect...) then you will want to right shift the value three places.

However, assuming your coding in c, if all you want to do is print out a number in octal take your number and use %o in place of %i in the printf function.