About
Community
Bad Ideas
Drugs
Ego
Erotica
Fringe
Society
Technology
register | bbs | search | rss | faq | about
meet up | add to del.icio.us | digg it
Go Back   Community > Science > Mad Scientists
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

Mad Scientists Science and Mathematics discussion-- theories, arguments, citations, proofs and pudding.

Reply
 
Thread Tools Display Modes
 #1 
Old 2008-10-23, 15:54
Regular
 
......oo00ooo<
Default bitwise operations

Okay, I've been wanting to do bitwise operations on my graphing calculator in just a single line, but I don't know how. I know a couple are possible to do but I'm not sure of the others.

If you don't know what I'm talking about, a bitwise operation just divides up a number into binary digits and applies a certain boolean expression to each individual bit. You can try it on the Windows calc.exe program in scientific mode.

Say you want to find
31 AND 55

First you convert them into binary.
11111 AND 1101111

Then you apply the AND operation to each set of bits. Where both are 1, you get an output of 1. If either bit is zero, you get zero as the result.

011111 = 31
110111 = 55
======
010111 = 23

Now, certain ones I can do in a single mathematical expressioin, such as left shift, right shift, and not. For not, you simply take the number of bits you're doing it for, say N, then find 2^(N)-1 which will give you a string of 1's in binary. Then subtract your number from that and you've applied not to it.

Say we want to find not(312) with 10 bits
2^(10)-1 = 1023 = 1111111111
312 = 100111000

1023
-312
====
711

or, in binary

not(0100111000) = 1011000111 = 711

For shifting bits to the left or the right, you just multiply or divide by 2 and knock off the remainder if shifting to the right.

But for stuff like AND, OR, and XOR I haven't found an easy way to do it yet. Is there such a way?
 #2 
Old 2008-10-26, 03:09
suicidejack suicidejack is offline
Regular
 
Default Re: bitwise operations

It depends on your calculator, but if it's programmable you can try the following:

and_b(x,y):
z := 0
m := 0.5
while ( x > 0 and y > 0 ):
a := mod(x,2) // x (mod 2)
b := mod(y,2)
c := a * b
z := z / 2 + c
x := floor(x/2)
y := floor(x/2)
m := m * 2
return z * m


This won't work for really big numbers, but as long as x and y can fit without loss in whatever the floating-point type is, this should work.

For or_b(), you can use "while ( x > 0 or y > 0 )" and "c := 1 - ((1-a)*(1-b))" (De Morgan's law), and for xor_b() you can use the identity "a^b = a&~b | ~a&b".

Hope this helps.
 
To the best of our knowledge, the text on this page may be freely reproduced and distributed.
 

totse.com certificate signatures
 
 
About | Community | Bad Ideas | Drugs | Ego | Erotica | Fringe | Society | Technology
Hot Topics