Subj : Color parsing
To : Kirkman
From : echicken
Date : Sun Dec 03 2017 03:28 pm
Re: Color parsing
By: Kirkman to All on Sun Dec 03 2017 13:21:29
Ki> If I have a Synchronet color value that's already been set (for example, I
Ki> read the .attr of a character in a frame), how can I parse it to determine
Ki> the foreground color and background color?
Ki> I imagine it requires using bitwise operators. I've never really
Ki> understood that part.
A colour attribute byte has a bunch of information packed into it, so you need
to mask out various subfields to see what values they hold.
The foreground colour is in the lower three bits of the byte.
var fg = attr&7; // 7 is essentially (1<<0)|(1<<1)|(1<<2)
The 'high' (or 'bold' or 'bright') status of the foreground colour is in bit 3:
var b = attr&HIGH; // Bright if > 0; HIGH is 8 or (1<<3) or 0x08
The background colour is bits 4 through 6:
var bg = attr&(7<<4);
Lastly there's the BLINK attribute, 128 or (1<<7) or 0x80:
var blink = attr&BLINK; // Blinking if > 0, else this is inoffensive text.
When you want to parse it there are a few options:
switch (fg|b) {
case BLUE:
break;
case LIGHTBLUE:
break;
// and so on
default:
break;
}
switch (bg) {
case BG_BLUE:
break;
// and so on
default:
break;
}
You could get away with using the same switch () for either one, but you would
have to shift the bg value over. The background colours are the same as the
foreground colours, just shifted 4 bits to the left:
function get_colour(c) {
switch (c) {
case BLUE:
break;
case LIGHTBLUE:
break;
// and so on
default:
break;
}
}
var fgc = get_colour(fg|b);
var bgc = get_colour(bg>>4);
Bitwise stuff takes some getting used to, but is easy enough once you get the
hang of it.
(I may have made several mistakes in the above, I'm just going from memory.)