1

I'm playing around with handling stuff in bit values while on a side project for learning. I'm unsure if what I'm doing is correct.

I have an object, which contains a list of bit values:

const bitVal = {
   food_item_1: 0x04,
   food_item_2: 0x08,
   food_item_3: 0x40
}

and so on.

I have an operation that when a user selects a combination of food items, it will add these values together like so

bitValue.food_item_1 | bitValue.food_item_3

and then i'll save this in the database.

My issue is, when I then get the bit values back. How do i figure out what items make up the bit number?

So food item 1 and food item 2 = 68. Based on that, when i get, 68 back from the DB how would i figure out what two, or three (there can be more than two, example is just two) is used?

My first attempt, is a function that iterates over all the values in the bitValue object and computes each one and see if it equals the value in the DB.

Issue here is. If i have 10 or so values in that bit field, that's a lot of computation to figure it out.

Is there a better way of handling this?

1 Answer 1

1

You could iterate the values and perform a bitwise AND with the combined value for a truthy check.

const
    bitVal = { food_item_1: 0x04, food_item_2: 0x08, food_item_3: 0x40 },
    value = 68;
    
Object.entries(bitVal).forEach(([k, v]) => {
    if (v & value) {
        console.log(k);
    }
});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.