When to use white text on top of a color for readability?

I am setting the background of a textbox to some variable color.

I know the hex/rgb of the color I'm setting the background to.

Normally the text is black (or very very dark gray).

On some colors, it would be far easier to read the text if it were white instead of black.

How can it be programmatically decided, given a hex/rgb color, whether white or black text would be more readable if placed on top of it?