Bit wise Minipulation

Im doing a project and trying to just get started i feel if i can see how the first part is done i can do the rest from there.

The object is to & two numbers together with out using & its self and instead only using | and ~. If any one could help it would be appreciated.
closed account (3hM2Nwbp)
Good question, I haven't ever thought of it, but after a quick think, this logic seems to work.

A AND B

NOT ( NOT(A) OR NOT(B))

So A and B is equivalent to the opposite of not A or not B.

Try it for yourself:

http://instacalc.com/



5555 & 74325 = 17
~(~5555 | ~74325) = 17

thank you :) ill try it, thats what i was thinking after reading about morgans law. I just didnt think about noting the entire thing i just had ~x|~y and it just didnt seem right

and if you like those there are a bunch of really hard ones i could toss at you haha ;).

for example get the nth byte of a number x, im pretty sure you use shifts but im not sure which ones or how exactly to return just that byte

whats making all of these so hard is we cant use loops or if statments.
Last edited on
for getting the nth byt of x would you right shift it by the n and then divide it by something? logically i feel like that works but idk what i would divide it by, i was thinking some power of two, but im lost.

this is the example given: getByte(0x12345678,1) = 0x56
Last edited on
~(~(x>>n)|~1)

One time, I tried implementing addition without using +. After compiling with optimizations, the compiler decided to change x<<=1 to x+=x, rendering all my efforts pointless.

Also, normally one implements things with NAND, as it's the cheapest type of gate (or so my electronics teacher told me), and because it can be used by itself to implement all other gates.
Last edited on
~(~(x>>n)|~1)

One time, I tried implementing addition without using +. After compiling with optimizations, the compiler decided to change x<<=1 to x+=x, rendering all my efforts pointless.

Also, normally one implements things with NAND, as it's the cheapest type of gate (or so my electronics teacher told me), and because it can be used by itself to implement all other gates.


to be honest im not sure whats going on there, i thought about left shifting it by n and then right shifting by n*2 but then i realized that that would only work for positive numbers
n = 0010 1110 (binary)
We want the 6th bit of n from the right, 6th least significant bit (or 5th if 0th is the LSB)
m = n >> 5;
Now m == ____ _001 (binary)
All _'s are new bits set by default to 0 so m == 0000 0001
"Strip" all other bits by and-ing with 1 == 0000 0001 (binary)
a = m & 1
Now a == 1 meaning that the 6th bit of n is 1 (on, true)
We can write this as bit = (x >> n) & 1

sorthon123 wrote:
...[I] realized that that would only work for positive numbers
Um... Getting the bit of a byte/word/dword/qword/etc... is not effected by what type of data you will interpret it as.
Topic archived. No new replies allowed.