How to set bits in a variable

I want to know how to un/set bits in a message/variable.

What I find is not clear for me to understand.

Any good?

Thanks, but Mr Stupid is not really getting it.

Sorry, but could you give a better example of how to set a bit?

For the sake of it: bit 2.


There is a node contrib-bitunloader that does a lot of what you are asking. Even if you don't use the node itself you could crack it open and look at the code. NOTE: it also loads a second node called bit unloader that may provide useful code

function setBit(number, bitPosition) {
  return number | (1 << bitPosition);

var currentVal = 0;
var newVal = setBit(currentVal, 2)
1 Like

So I need to put the function above the code, not below?

(Thanks. Shall try now)

As a professional bit-twiddler (writing device drivers and the like) I can say it's a skill worth learning for anything to do with low-level coding.

I think @Steve-Mcl has provided the basic functions above, but additionally it's worth learning how the bit values go, and ways to represent them.

Decimal probably isn't the easiest way to understand them. Although it starts easily with 1, 2, 4, 8 etc., by the time you get up to 16384, 32768 and so on, it's hard to keep track.

Hexadecimal ("hex") is a lot easier, since it goes in groups of 4 bits 0x01, 0x02, 0x04, 0x08, then shift to the next group - 0x10, 0x20, 0x40, 0x80, and so on.

Something else I also use regularly is constants for specific bit positions or bit-fields, e.g.

const WRITE_ENABLE = 0x0200;

then use the name rather than the value (which you'll forget or get wrong occasionally anyway).

Once you get your head round the basics it'll all fall into place, but just ask if you get stuck.

Doesn't matter,scope%20is%20global%20or%20local.


Yes, I do get what you are saying. But I am facing a problem (see other thread if you want) and it is becoming painfully clear I need to set bits to indicate status.

So I am going to use bits to reflect the status of the devices.

Yes, I need to learn about it more but for me at this stage, I am not wanting to bite off more than I can chew - though I guess I kind of have if I am asking the question.

Thanks again.

I got tripped with how to call the function but with that latest post, I have it working in a way I like.

I'll put some effort now into implementing what I just learnt into application.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.