I was trying to sort a series of polar coordinates by compass direction: everything in the N sector, then NNE, NE, ENE, E, … This is trickier than it looks, since the North sector includes angles between 348.75° and 11.25°.

It’s easier to think of the problem instead of being one of *N* bins centred on 0°, but rather one of *2N* bins starting at 0°. Then, all one needs to do is shift everything round by one of these half bins (so +1, modulo *2N*), then divide the number of bins back to the number we want. Done!

Here’s some code to do it. It may look like C-like pseudocode, but it’s real live AWK:

function bin(angle,nbins){ return int(((int(angle/(360.0/(nbins*2)))+1)%(nbins*2))/2); }

You probably want the angles to be between 0..360°. But you knew that.