Lurker News
Paste the following into the console of any HN page - for annotated avatars on all HN comments. (self contained code)

  for(u of document.querySelectorAll('.hnuser'))for(u.prepend(c=document.createElement('canvas')),x=c.getContext('2d'),c.width=18,c.height=14,s=u.innerText,r=1,i=28+s.length;i--;i<28?r>>>29>X*X/3+Y/2&&x.fillRect(6+2*X,2*Y,2,2)&x.fillRect(6-2*X,2*Y,2,2):r+=s.charCodeAt(i-28,x.fillStyle='#'+(r>>8&0xFFFFFF).toString(16)))r^=r<<13,r^=r>>>17,r^=r<<5,X=i&3,Y=i>>2

Comments (493) 108 threads

Earlier comments
lexicality5 replies#
These are very cute, but I'm mildly annoyed that mine is basically invisible
XzAeRosho2 replies#
That sucks.

I was thinking of ways to prevent that, but without adding a bunch of ifs it kind of kills the minimalistic approach of the original code.

snek_case#
You can have an outer loop that checks how many pixels are set in the avatar and keeps trying to generate a new avatar with a different seed until it's not (rejection sampling). As long as the probability of the avatar being too empty is small it should be fast.
yoz-y#
The main problem is probably the color, maybe somehow capping the maximum brightness would be doable.
xoxxala#
You do stand out now!
riidom#
actually your avatar looks like a mildly annoyed raccoon!
supermatt5 replies#
Ive been a dev for over 2 decades but I still cant grok bitwise operators - anyone have a reference that may help with that?
supermatt5 replies#
Thanks, but its still a bit confusing for me. Im looking for a really dumbed down kind of approach: input, operator, visual explanation of what its doing, output. Im a really bad learner, and didnt study computer science or anything. Ive never had a reason to touch binary, so find these operators unintuitive.
stavros#
If you don't know about the binary representation, you won't be able to learn binary operators. If you do, they're fairly straightforward. I'd suggest learning about binary first.
bspammer2 replies#
I think before you can understand binary operators, you’ll need to understand binary itself and how to convert it to and from decimal. This crash course computer science video may help: https://youtu.be/1GSjbWt0c9M

In fact the whole course might be useful!

Continue this thread — 2 replies

omegabravo1 reply#
the wiki is a visual representation. The representation is 0s and 1s.

The use case for bitwise operations is to control the value of 1 bit.
Consider if you have a 0000 1000 value. It's mapped to hardware output so the 4th LED is on. Now you want to turn the 5th on, and the 4th off. You would use a left shift so the output becomes 0001 0000.
That's all there is to it. Bitwise operators operate on bits, not bytes. Because computers operate on bytes, and you can't address a bit - you have to modify bytes to accomplish your goal.

Continue this thread — 1 reply

Aardwolf#
Try thinking about the equivalent in decimal:

A left shift in binary adds a 0 at the end which multiplies by 2 (binary = 2)
In decimal, the equivalent, adding a 0 at the end, multiplies by ten (decimal = ten)

Beltalowda#
You'll just have to use it in actual programs to really understand it. You can't properly understand `if` and `for` either just by reading some doc page about it, you can't become a guitarist just by reading about technique, you don't become a carpenter just about reading about it, etc. So don't feel bad if you're confused by just reading that page.
CapsAdmin2 replies#
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.

supermatt#
> 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.

dividuum#
> 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.

denysvitali2 replies#
<< means shift left (moves the bits to the left side)

1 << 1 = 2 because (0001 << 1 = 0010 = 2)
3 << 1 = 6 because (0011 << 1 = 0110 = 6)
>> works in the same way
2 >> 1 = 1 because (0010 >> 1 = 0001)
The other operators are exactly the same you'd find in electronics (and boolean algebra):
~ is the NOT operator
& is the AND operator
^ is the XOR operator
Sorry, I don't have a visual representation for this (I haven't looked for a link) but I would strongly suggest to write it down on paper and do some small exercises (checking with the result then on your favorite programming language).
On a day to day basis, you'd likely not use these operators at all, but as soon as you start decoding protocols or working on a bit-level, those are super useful!
I would suggest trying to decode a bitstream protocol to really grasp the concepts: you'd use masks and bitwise operators a lot :)
---
Edit: some useful links I've found: https://www.interviewcake.com/concept/java/bit-shift

ElectronCharge#
Testing…
Cthulhu_#
It helps if you look into bits and binary arithmetic; I learned it from the appendix of my school book Structured Computer Organization. Binary and binary arithmetic is probably the best place to start.
hideo#
Reading didn't do the trick for me. It clicked when I started writing code to accomplish tasks, like assignments or coding puzzles, that required bitwise operations.

I can't find any of my undergrad coursework online but here's an alternative that looks like a nice intro https://web.stanford.edu/class/archive/cs/cs107/cs107.1194/l...

tomxor5 replies#
This was inspired by @frncsdrk's submission from earlier today [0]. The generative concepts used were inspired by and derived from dweets from @KilledByAPixel and @FireFly [1] [2] [3]

The concept is to use HN usernames as the seed into a deterministic avatar generator. This generator is built from the famously simple xorshift32 PRNG, which both provides a random variable for the image generator steps, and "pseudo-hashes" the seed string to provide the initial PRNG state using a non-linear step (adding each codepoint - which is likely not very robust against collisions compared to proper hashing algorithms, but is simple and good enough).
The image generation part is a probability distribution with mirrored pixels... specifically: r>>>29 > X*X/3+Y/2 where the left side is 3 of the upper bits of the PRNG state (providing a random integer 0-7), and the right side is the squared distance from the centre for X + the linear distance from the top for Y. i.e the further from the top centre the pixel is, the less likely it will be filled, but linearly for Y and squared for X.
Un-golfed version:

    for (const u of document.querySelectorAll('.hnuser')) {
        const p=2;
        const c=document.createElement('canvas');
        const x=c.getContext('2d');
            c.width=p*7, c.height=p*7;
            u.parentElement.prepend(c);
        for (let s=u.innerText, r=1, i=28+s.length; i--;) {
            // xorshift32
            r^=r<<13, r^=r>>>17, r^=r<<5;
            const X=i&3, Y=i>>2;
            if (i >= 28) {
                // seed state
                r+=s.charCodeAt(i-28);
                x.fillStyle='#'+(r>>8&0xFFFFFF)
                .toString(16).padStart(0, 6);
            } else {
                // draw pixel
                if (r>>>29 > X*X/3+Y/2)
                x.fillRect(p*3+p*X, p*Y, p, p),
                x.fillRect(p*3-p*X, p*Y, p, p);
            }
        }
    }
Was fun to play with, but also surprisingly helpful in following discussions.

It's worth mentioning these were heavily inspired by three particular dweets by @KilledByAPixel and @FireFly:
[1] https://www.dwitter.net/d/3078
[2] https://www.dwitter.net/d/19786
[3] https://www.dwitter.net/d/23326
[0] https://news.ycombinator.com/item?id=30660316

Lorin1 reply#
I've been following Frank Force (KilledByAPixel) for quite some time now, he's on the forefront of generative design via HTML canvas.
tomxor#
Yeah! he's done a deep dive into it more recently. Attempting to follow his twitter thread at the moment is like trying to consume a fire-hydrant of generative art :D hard to keep up, but looks amazing.
usrme1 reply#
There's actually a slight difference between the golfed and un-golfed version: the un-golfed adds the avatar to the beginning of the line with the username, whereas the golfed version adds it right next to the username. I actually find it to be more visually appealing at the beginning of the line, so I'm sticking with that in my Greasemonkey script.

To anyone interested, I've added links to how the un-golfed version looks with Dark Reader enabled[1] and how it looks without Dark Reader[2]. To clarify, I've set my zoom level for Hacker News to 150% as I find the default to not be conducive to reading.
---
[1]: https://i.imgur.com/hw9pn0l.png
[2]: https://i.imgur.com/z3jV2NZ.png

tomxor#
Yup, i noticed an opportunity to make it smaller while golfing.

There is one advantage of the golfed version, which is that it will also inject avatars wherever it finds the .hnuser class, including on other pages.

chrisdsaldivar#
I've never heard of dweets/dwitter before; thanks for sharing. For anyone else:

Dwitter.net is a challenge to see what awesomeness you can create when limited to only 140 characters of javascript and a canvas. Give it a go!
https://www.dwitter.net/

chrismorgan1 reply#
Your minified version lacks the .padStart(0, 6) you have in this comment, without which colour selection fails in just under 1⁄16 of cases, yielding black. (Or in just under 1⁄256 of cases, a semi-transparent colour!)
tomxor#
Thanks, I know it's absent (it's golfed not minified), which means I manually manipulated it to make as small as possible which sometimes means making "concessions" where things are not ideally preserved - But in retrospect you're probably right, I was being too aggressive and should have either left the padding in or replaced it with some guarantee of formatting length length like "&FFF|0x111"
CapsAdmin1 reply#
further ungolfed:

  for (const huser of document.querySelectorAll(".hnuser")) {
    const s = huser.innerText;
    const p = 2;
    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");

    canvas.width = p * 7;
    canvas.height = p * 7;

    huser.parentElement.prepend(canvas);

    {
      const xorshift32 = (n) => {
        n ^= n << 13;
        n ^= n >>> 17;
        n ^= n << 5;
        return n;
      };

      const seedSteps = 28;

      let seed = 1;
      for (let i = seedSteps + s.length; i >= seedSteps; i--) {
        seed = xorshift32(seed);
        seed += s.charCodeAt(i - seedSteps);
      }

      context.fillStyle =
        "#" + ((seed >> 8) & 0xffffff).toString(16).padStart(0, 6);

      for (let i = seedSteps - 1; i > 0; i--) {
        // continue the seed
        seed = xorshift32(seed);

        const X = i & 3;
        const Y = i >> 2;

        if (seed >>> (seedSteps + 1) > (X * X) / 3 + Y / 2) {
          context.fillRect(p * 3 + p * X, p * Y, p, p);
          context.fillRect(p * 3 - p * X, p * Y, p, p);
        }
      }
    }
  }
efraim#
You're off by one in the initial seed step. Change

for (let i = seedSteps + s.length; i >= seedSteps; i--) to for (let i = seedSteps + s.length - 1; i >= seedSteps; i--)
The original is not using the for loop in the usual way so i starts off one smaller than expected.

lekevicius2 replies#
Looks way better if you add style="image-rendering: pixelated;" to the canvas. Crisp edges on every display.
vihren#
Yup, definitely second that. With that change I can definitely imagine this as a user option in the settings. Reading is so much easier.

(also wanted to see my avatar)

toqy#
It does! Here's a bookmarklet with that added (generated here: https://caiorss.github.io/bookmarklet-maker/)

javascript:(function()%7Bfor(u%20of%20document.querySelectorAll('.hnuser'))for(u.prepend(c%3Ddocument.createElement('canvas'))%2Cx%3Dc.getContext('2d')%2Cc.width%3D18%2Cc.height%3D14%2Cc.style.imageRendering%3D%22pixelated%22%2Cs%3Du.innerText%2Cr%3D1%2Ci%3D28%2Bs.length%3Bi--%3Bi%3C28%3Fr%3E%3E%3E29%3EXX%2F3%2BY%2F2%26%26x.fillRect(6%2B2X%2C2Y%2C2%2C2)%26x.fillRect(6-2X%2C2*Y%2C2%2C2)%3Ar%2B%3Ds.charCodeAt(i-28%2Cx.fillStyle%3D'%23'%2B(r%3E%3E8%260xFFFFFF).toString(16)))r%5E%3Dr%3C%3C13%2Cr%5E%3Dr%3E%3E%3E17%2Cr%5E%3Dr%3C%3C5%2CX%3Di%263%2CY%3Di%3E%3E2%7D)()%3B

Load more comments