Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I struggled with this as well. Now I'm a bit rusty as I haven't used it for a while, but what really helped me was to start thinking about binary numbers more as strings. It also really helps me to visualize binary operations in binary space, not hex or decimal. That's still very confusing to me.

For example left shift by 1 on this 8 bit number (decimal is 32)

00100000

you just shift all the numbers to the left

01000000

--------

There's some wrapping behavior of course. Like what happens if you left shift 3 here? If it's an unsigned 8 bit number the 1 would teleport to the right side.

00000001

--------

the logical operators work like this (read downwards)

00010000 AND

00010000 =

00010000

--------

00001000 AND

00010000 =

00000000

--------

00001000 OR

00010000 =

00011000

With this in mind, I found it to be a good exercise to implement common bitwise operators that work on fixed length strings with some tests against the real binary operators in your favorite language.



> There's some wrapping behavior of course. [...] the 1 would teleport to the right side.

Not really. Shifting by definition discards 1 bits once they pass either "edge" of the value. The wrapping you describe only happens with rotation operations. In the languages I know they don't have fancy short hand syntax like shifting does.


> It also really helps me to visualize binary operations in binary space, not hex or decimal. That's still very confusing to me.

Yeah, I think thats a major part of the problem for me. When im looking at these code snippets (as per ungolfed version of the post in a comment below) applying the operators to integers i just cant understand what it is they are trying to achieve, so I am unable to grok the purpose/intent. Even with the explanations given here im not sure why its doing what its doing - and I dont seem to encounter that issue outside of bitwise operators.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: