# Thread: Palindromes and Bitwise operators

1. ## Palindromes and Bitwise operators

Hi,

I've been learning to use the bitwise operators and i've been doing some exercises without problems until i came across with this one:

"write a program that finds USING BITWISE OPERATORS whether a number entered by the user is a palindrome or not"

Does anyone have any idea of how to do it? 2. Originally Posted by Dr Tornillo "write a program that finds USING BITWISE OPERATORS whether a number entered by the user is a palindrome or not"
A palindrome in which base? If binary, it's easy. If decimal, it's stupidly difficult. 3. decimal…
yes, I know that it's quite difficult and that it doesn't have much sense to do it that way 4. Originally Posted by Dr Tornillo decimal
yes, I know that it's quite difficult and that it doesn't have much sense to do it that way
Well, you'd have to implement division and modulo by 10 using bitwise operators. Once you have that, the rest is cake.

But personally, I think it's a silly exercise. I think you'll gain a bunch of frustration, not understanding. 5. If it's binary, then it's dead easy, as brewbuck says: Just shift out a number down one side, and pick the bits up into a new number. If the two numbers match, it's a palindrome. For example 5, 6, 9, 27 are binary palindromes.

Doing divide/modulo in base 10 with only shifts and logical operations seem difficult (but obviously possible, because "and" and "or" is nearly the only thing that is available in transistor logic, so that's how a processor would do add, subtract, multiply, etc - but there are a lot of transistors in a modern processor just because it's so complicated to do these things with just these simple operations).

--
Mats 6. How is 6 ( 110) a palindrome? 7. Put a 0 on the front. lol.... Sorry, you asked.  8. Bitwise operations are necessary for much low-level programming, such as writing device drivers, low-level graphics, communications protocol packet assembly and decoding.

Although machines often have efficient built-in instructions for performing arithmetic and logical operations, in fact all these operations can be performed just by combining the bitwise operators and zero-testing in various ways. For example, here is a pseudocode example showing how to multiply two arbitrary integers a and b using only bitshifts and addition:

c := 0
while b ≠ 0
if (b and 1) ≠ 0
c := c + a
shift a left by one
shift b right by one

return c
--Wikipedia example in psuedocode
I assume divide is just the reverse? 9. Originally Posted by manofsteel972 I assume divide is just the reverse?
The code you showed uses "+" to add... :-)

And yes, divide is similar in that you shift, but you also need to compare (but perhaps that CAN be done with a and operation).

--
Mats Popular pages Recent additions 