How to parse hex codes

Hi all! I’m new to PixelBlaze and don’t have a lot of experience with JavaScript. I’m wondering how you can use a hex code like you’d find in HTML (e.g. #FF0A52) either in a color picker or by pasting it into the pattern directly. It seems numbers can’t go beyond 16.16 fixed point format, and strings are disabled. I’d like to start with a simple static color for my LEDs: just paste in a hex code you find, and boom, the lights update. Ultimately, I’d love to code gradients or more complex patterns, but I need to start with hex codes to match color styles that I’m using.

I couldn’t find how to do this in the examples or forum, so any help would be appreciated!

The main issue is that Pixelbaze doesn’t support strings! But also what you mentioned, which is that we need 24 bits for HTML colors, but we typically use the fractional 16 bits to express and output out values for r, g, & b or h, s, & v.

I haven’t seen any patterns do this before, and apologies because I don’t have a Pixelblaze with me to test, but I suspect something like this should work:

// HTML Color #FF0A52
export var color = [0xFF, 0x0A, 0x52]

export function render(index) {
  rgb(color[0]/255, color[1]/255, color[2]/255)
}
1 Like

Thanks! I was able to do it with separate R, G, B values. The array is a good idea!

@wizard how good is your optimizing compiler? Does it detect and collapse constant array values? :smiley:

If not, this would be written more performantly as:

// HTML Color #FF0A52
export var color = [0xFF, 0x0A, 0x52].map((x) => x / 255)

export function render(index) {
  rgb(color[0], color[1], color[2])
}

… saving 3 divisions per pixel.

(I didn’t test that use of .map on an array literal, but putting /255 in each entry would work at the expense of readability and maintainability)

You’re so funny… I totally was debating doing it this way but was wondering “what’s the clearest way to communicate this concept”.

1 Like

I’m glad you didn’t. I hope that more than one person learned something about pattern optimization from this exchange. :heart:

Optimizing compiler? What fun would that leave us?!?

Use the mutate method to change an array in place. The map method in JavaScript would create a new array, and we don’t want that (and it doesn’t exist in PB’s subset.)

We also have a mapTo when you do need a copy instead of a change in place, that works on 2 arrays.

1 Like

Does mutate also work on a literal array,

export var color = [0xFF, 0x0A, 0x52].mutate((x) => x / 255)

or do we have to do this?

export var color = [0xFF, 0x0A, 0x52]
color.mutate((x) => x / 255)
1 Like

A literal array expression is just an efficient way to make an array with some values in it. They are still mutable.