The beauty of bitwise AND
medium.com
medium.com
- convert x and y from decimal to binary
- calculate x AND y at each digit (by using the property that x AND y is isomorphic to multiplication mod 2)
- convert back to decimal.
Instead of trying to understand bitwise AND in this way, we could try building the equivalent operation in base 10, and see where that leads us. One simple way of achieving this is by simply saying that x AND Y is digit-wise MIN, and x OR y is digit-wise MAX.
Note how, under that interpretation, this works in both binary and decimal (or hex, or octal, or whatever other base you want:
101 AND 110 = 100
101 OR 110 = 111
Or using digits not available in binary:
124 AND 310 = 110
124 OR 310 = 324
Again, this works independently of whether you're using octal, decimal, hex, or something else >= 5.
They are called there Zadeh OR and Zadeh AND - by the mathematician https://en.wikipedia.org/wiki/Lotfi_A._Zadeh
I must confess to being quite chuffed that homegarlic has since commented that this is consistent with how Zadeh fuzzy set theory works (though that uses reals in the [0,1] range rather than modular arithmetic).
If the abstraction doesn't have generally applicable higher-level properties, it's probably not worth abstracting.
After all, bit-wise AND is only one of 16 possible two-argument bit functions. Shall we create a digit analog for all 16 of them?
Given that, looking at decimal digit-wise AND under that lens isn't about introducing a new abstraction, it's about applying an existing abstraction to a new domain.
Let's use distributivity of AND over OR:
a & (b | c) = a & b | a & c
This also works in the abstraction of Boolean algebra to normal algebra: a * (b + c) = a * b + a * c
What about with your digit MIN/MAX abstraction: MIN(a,MAX(b,c)) = MIN(MAX(a,b),MAX(a,c))
Well... No, this does not generally hold. If b and c are both larger than a, then this equality fails.Distributivity is a pretty important property. Without it, your MIN/MAX algebra just has commutivity and associativity which arguably aren't very unique considering all other possible commutive/associative functions. In any case, losing a property dramatically decreases the usefulness of your algebraic abstraction.
Another wart in your abstraction is the missing NOT operation, further deteriorating its usefulness.
Just because the MIN abstraction works for the AND case, that's not enough to make it a worthwhile abstraction. What happens when you want to do more complex yet natural operations like a & (b | c)? In the same vein, AbstractManagerFactoryFactory may seem elegant now, but it may make it harder for new code to do trivial things down the road.
MIN(a,MAX(b,c)) = MAX(MIN(a,b),MIN(a,c)) MAX(a,MIN(b,c)) = MIN(MAX(a,b),MAX(a,c))
so it is even more useful than normal algebra :pGeneralization of ANDs and ORs is called t-norms and t-conorms (s-norms). They have to satisfy laws of monotonicity, commutativity and associativity.
So all kinds of magical ANDs and ORs spawn to meet the requirements.
I'm not really a fan of fuzzy logic but it really is a nice exercise in mathematics.
http://code.kx.com/wiki/Reference/Bar http://code.kx.com/wiki/Reference/Ampersand
What I suggested was that that way of operating on the representation of the number would work on any base in a way that is consistent (but, importantly, doesn't yield the same numerical result!) with the binary version.
What?! What exactly is at the memory address that you think it's converting?
1 - https://d262ilb51hltx0.cloudfront.net/max/800/1*Y5WC--jvMMdU...
That's what I'm railing against. If your objective is to understand how bitwise-AND works, trying to decipher it directly in base-10 is folly. I'm not a fan of the graphical approach taken by the post either, and prefer the algebraic way out, which is why I proposed an algebraic base-10 (any-base, really) version.
Bit-wise arithmetic is great because it's operations are compatible with propositional calculus,- but I cannot see how you can do anything productive with min/max-wise defined AND/OR for base10. For example how to do you determine 324 XOR 310 in your notation?
NOT d = 9 - d
Similar to NOT b = 1 - b
for binary digits. And in fuzzy logic.Taking the logic identity
a XOR b = ( a AND NOT b ) OR ( NOT a AND b )
it would be MAX( MIN( a, NOT( b ) ), MIN( NOT( a ), b ) )I would argue that while bitwise operations are indeed more easily represented/computed in base 2 than in base 10, they do act on the 'number itself', whichever base you then represent this number in. ... at least in the approach I took, where I treat bit strings as representations of 'numbers', specifically positive integers. If you think of such operations as manipulating 'strings' of characters - whatever character set those are taken from - rather than numbers then indeed we indeed arrive to different conclusions, and your digit-wise MIN generalization makes sense.
I think both approaches are meaningful, although conceptually different, and I have tried, however clumsily, to explain the 2 approaches in a previous post (https://medium.com/biffures/bits-101-120f75aeb75a#.fc93no6od) before settling for the 'number' approach for this post.
I am actually not a proponent of using base 10 as the standard view for bitwise operations, I merely use that base to show that the function looks complicated in base 10 and brings little further intuition on what pattern AND follows. Note that the rest of the article and all visualizations are NOT base-dependent and do not use the base-10 formula. (I did write my numbers in base-10 in the sketches simply out of convenience, but feel free to translate to any base).
Is this revolutionary? Certainly not. But I do think the graphs look cool, and I was happy to share them. Hope this clarifies some of the thinking behind the post; and thanks for the constructive thoughts! - seems like I can do plenty of read-up .-)
C
Actually, looking at the XOR, AND, OR textures side by side, it's easy to gain more intuition for them.
I definitely recommend reading some of the articles at [2], they're pretty entertaining and straight-forward.
> But who'd want to generate a 1024x1024 XOR texture anyway.
The article contains a 1024x1024 AND texture :)
https://en.wikipedia.org/wiki/File:Multigrade_operator_AND.s...
Back in the year 1992, when I was 9 years old, I participated in the first tour of Russian programming olympiad. The first challenge was this one:
"On the infinite coordinate grid (positive integers only), start with the number 0 in the cell with coordinates (0,0). Then, in each cell in the neighbourhood, write the largest integer that hadn't yet appeared in the same row or column. Repeat indefinitely.
Find the formula for obtaining the value inside any arbitrary cell in the grid."
I have filled a 16x16 grid using this definition manually (of course, the programming olympiad had nothing to do with computers — similar to whiteboard coding during the job interviews these days), and obtained similar pattern. As this task was by far the most interesting in the problem set, I have spent the entire allotted time trying to figure out the formula, without success — so I got 0 points and went out of the competition.
And now, 24 years later, I see the solution (not the AND; the pattern looks slightly different, perhaps XOR?) But I should have tried bitwise operations back then. Damn it!
(Note by the way, that the initial condition about (0,0) can be omitted -- at that point, there are no numbers in that row or column, so the smallest one available is 0!)
Topics you might want to look up: https://en.wikipedia.org/wiki/Combinatorial_game_theory https://en.wikipedia.org/wiki/Nim https://en.wikipedia.org/wiki/Sprague%E2%80%93Grundy_theorem https://en.wikipedia.org/wiki/Mex_(mathematics) https://en.wikipedia.org/wiki/Nimber
(In the quote below, he names the AND function "f", which in itself is a bit strange. What's wrong with "and" or ∧?)
f(a, b) produces at most a or b, whichever is greater:
f(a, b) ≤ max(a, b)
As far as I can tell, the result can never be greater than the smaller of a and b. I can't come up with a counterexample. Is there one?* assume WLOG `a = min(a, b)`
* `a & b` takes the set bits of `a` and produces a subset of them
* the value of an integer is `SUM 2^j` where the j-th bit is set
* removing positive elements from a sum can only make it smaller
* therefore & can only produce a value smaller than `a` (the minimum)
The post doesn't specify. Programming languages do define it over the negatives, however. I just didn't want anyone going into python and asserting that a & b >= min(a,b).
> there's no indication of how to encode negatives
Just do the standard thing: use 2s complement arithmetic [1]. More concretely: set b to infinity and take the limit under the 2-adic metric [2]. For example, -2 & -1 has partial sums 0, 10, 110, 1110, 11110, etc. It's limiting to ...1111110, which is the 2's complement representation of -2.
sum_n^b 2^n (floor(0/2^n) mod 2) (floor(-1/2^n) mod 2)
sum_n^b 2^n * 0 * 1
sum_n^b 0
0 f(-1, -1)
= sum_{n=0}^b 2^n (floor(-1/2^n) mod 2) (floor(-1/2^n) mod 2)
= sum_{n=0}^b 2^n * 1 * 1
= 1 + 10 + 100 + 1000 + ... [in binary]
= ...11111 [in the 2-adics]
= -1I'm going to go out on a limb and guess that it is of some habitual relevance to a mathematician, since he mentions the identity function (not really relevant here either), but that the material he actually explains here doesn't do anything to justify its appearance.
However, I cannot present to you the crucial difference between the maximum of two numbers and the minimum of two numbers that explains what he was thinking. This must exist for my hypothesized explanation to make sense.
It's worse than that; he mentions the identity function only to make a gross error about it. The identity function on (a, a) is (a, a), not a.
If you want extra precision, a -> f(a, a) is Id.
Knowing that helped me understand one property of the chart, never said that was the most stunning of properties, and the best articulated one :-)
What does this mean?
The law x AND x = x is called the idempotence law.
Nothing to do with the identity function.
'∧' usually denotes the logical AND operator, which does not operate on integer values, (i.e. writing 22 ∧ 78 = 6 is weird). So it's not a bad idea to give this function a different name.
He could have made that explicit though.
[1] https://commons.wikimedia.org/wiki/Category:Binary_ring_diag...
But ^ and ∧ are different.
One interesting application of bitwise AND is in cryptography, particularly LRX (logical rotations and xor) algorithms popularized by Keccak/SHA-3. By using only these limited operations, masking (blinding) becomes much more efficient that makes various side channel attacks harder [0]. Several of the CAESAR AEAD competition candidates are LRX. NORX uses only AND, XOR, and rotation.
[0] - http://stackoverflow.com/questions/7199625/mathematical-equa...
http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4....
I'd go a little further: the complexity of the formula only demonstrates that trying to fit a square peg (bitwise boolean algebra) into a round hole (numeric algebra) can cause things to get complicated.
In particular, the author seems to think that "math" means "numbers":
> the AND function is in fact mathematically non-trivial:
> The mathematical equivalent of AND
> Now, if you find that function dreadful — I am with you. When I first wrote it down, I found it both complicated and unhelpful; after formulating it, my mind was no closer to understanding the kind of pattern the AND function followed, if any.
> Ignoring the complex math formula above, we can still find a number of interesting properties regarding the AND function.
This implies that bitwise boolean algebra is somehow 'not math', and the complex formula somehow 'is math'. In fact math can deal with anything that's precisely defined, and includes fields like geometry, topology, logic, category theory, universal algebra, set theory, type theory, etc. which aren't particularly related to numbers. Whilst we could represent, say, logic, using a numerical formula (e.g. based on Goedel numbers) it's usually the wrong thing to do ;)
I think this may be a side-effect of the poor state of math education; i.e. we're taught to perform numerical calculations and not much else. :(
AND is not multiplication in base 2 :)
The point of the article was to make sense of the apparent complicatedness of the math formula through nice visuals that help humans understand what AND does number-wise.
I may have used the terms math vs. numbers loosely, but this seemed to be the terms most people would understand - and a vocabulary used in other places (Wikipedia, though maybe hardly a reference?). I have tried to explain my "bit string" vs "number" approach [in this other article](https://medium.com/biffures/bits-101-120f75aeb75a#.gz4ka3t7k) if you are interested.
Really not implying that boolean algebra is not math though - and I am pretty sure this has nothing to do with the 'poor state of math education'.
The operation, mathematically, is extremely simple.
The point of the article is to switch bases (exploring the many facets).
Per my previous thoughts, "the binary notation is a contingency, useful to understand and define specific functions that will run fast on computers given their binary architectures. However, because the notation does not convey meaning in itself, those numbers and functions are as well described in any arbitrary base, namely base 10 for humans, or base 16 (hexadecimal) for conciseness."
You're absolutely right, and this was my main problem; labelling the complicated version as 'math' seems to imply that the simple definitions, the wonderful patterns, etc. are somehow 'not math'.
> a decimal formula for a binary operation
It's not the base which makes it complicated; it's extracting each digit individually. Using the same approach to define a digit-wise operation in base 10 would be just as nasty, except you'd have powers of 10 instead of powers of 2, and mod 10 instead of mod 2.
In other words, just because decimal lets you write numbers like "946", it doesn't make it trivial to get the "9", "4" or "6" individually using 'highschool algebra'; you need to use mod, division, floor/subtraction, powers of ten, etc. just like that formula does for base 2.
Of course, if we don't stick to highschool algebra, it can be as trivial as we like. "The digits of 946" is a perfectly well defined mathematical/numerical operation, so we can just say that and we're done. Likewise, we can make a trivial formula for bitwise AND, like "x ^ y", by defining "^" as 'bitwise AND'.
In a way, formulas like that given in the article are only complicated because they're making assumptions about some operations being 'more fundamental' than others; but in "real" math (i.e. not highschool rote learning and number crunching), we're free to use whatever operations we want, as long as we define them precisely; "bitwise AND" is a perfectly fine definition, and just as good as "addition" or "multiplication".
You're perfectly welcome to define operators in terms of other things you consider to be 'more fundamental'; Russell and Whitehead famously did this in Principia Mathematica, considering sets to be more fundamental than arithmetic and requiring 300+ pages to reach a proof of "1 + 1 = 2".
Yet Goedel showed that no set of axioms is 'best', in which case you might as well use whichever ones make life easiest. When you're calling a formula "dreadful", it implies that you've not made your life easy ;)