In some languages, if you want to assign the number 10 to the variable x, you might write something like:
x = 10
This doesn’t work in brainfuck, as “x”, “10”, “=”, and the spaces between them are all ignored, they’re not part of brainfuck’s vocabulary. And there’s no special punctuation mark that stands for ten. What was once a given, a constant, now requires a programmatic strategy, and one with stylistic concerns. I can make an easy 36 or a clever 36 or a truly brainfucky 36 that’s short, elegant, and a challenge for anyone else to understand.
Let’s look at examples to make this more clear:
The easy way:
++++++++++++++++++++++++++++++++++++
When you start a brainfuck program, the memory space is all full of zeroes. Instead of x, there’s a byte you can think of as x and which you can get to by moving back and forth (you do that with > and < ). Once we’re at a place in memory we like, we can simply write out 36 plus signs, and there we have it.
Version 2:
++++++[>++++++<-]>
This is multiplying six by six. Here’s how it works:
A loop begins with [ and ends with ] and when the byte referred to just before the loop becomes zero, it ends. So we add six, jump to the right, add six, jump to the left, subtract one, then do this again and again until the left number counts down to zero, leaving us with six plus-signs executed six times (6 x 6) in the right number.
However, there are other, more clever ways to get to 36.
A byte can only hold a number from zero to 255. So another way of writing 36 is with 256 + 36 plus signs:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
This is called wrapping. You could keep going and add any multiple of 256 to this and get to the same place.
But this is just spinning the odometer. Things get more interesting when we use this technique in a loop:
Here, we add 2, move to the right and make that 2 as well. Then we move back to the left and add 7, and back to the right to add 2. We do this until the left number is evenly divisible by 256, which happens when we hit 1024. 7 * 146 + 2 = 1024. This means we’ve gone round the loop 146 times. 146 * 2 is 292. 292 - 256 = 36. So we’ve passed zero only once in the right variable, leaving us with the remainder of 36.
In Part 2, we’ll look at nested loops. In the mean time, there’s a fucking huge list of brainfuck constants.
New Tumblr on brainfuck and its legacy: languages & code art that build on brainfuck’s weirding of the communication between people and machines
Sorry for the double-repost, got the truncated version earlier…
Page 1 of 38