change individual bits in a byte

For general Flowcode discussion that does not belong in the other sections.
Post Reply
DirkB
Posts: 61
http://meble-kuchenne.info.pl
Joined: Thu Dec 10, 2020 3:55 pm
Been thanked: 4 times

change individual bits in a byte

Post by DirkB »

Hello,

How can I change individual bits in a byte?

Thank you
Dirk

mnfisher
Valued Contributor
Posts: 1008
Joined: Wed Dec 09, 2020 9:37 pm
Has thanked: 106 times
Been thanked: 520 times

Re: change individual bits in a byte

Post by mnfisher »

You use | (or) and & (and)

For example

.v = .v | (1 << 5) will set bit 5 in .v
.v = .v & ~(1 << 5) will clear bit 5

Martin

DirkB
Posts: 61
Joined: Thu Dec 10, 2020 3:55 pm
Been thanked: 4 times

Re: change individual bits in a byte

Post by DirkB »

Hello Martin,

many thanks for that. Is it also possible to set a bit in a byte by the value of a boolean variable,
like for example bit 5 (or any other bit) gets the value of the boolean variable?

thanks
Dirk

DirkB
Posts: 61
Joined: Thu Dec 10, 2020 3:55 pm
Been thanked: 4 times

Re: change individual bits in a byte

Post by DirkB »

Me again,
Reading a byte via var1 = var2 & 4 - (4 - 2) always gives the value of the bit,
such as bit 1 = 1(0), bit 2 = 2(0), bit 3 = 4(0), bit 4 = 8(0) etc. Can each bit
be read out as set (1) or not set (0)?

Dirk

mnfisher
Valued Contributor
Posts: 1008
Joined: Wed Dec 09, 2020 9:37 pm
Has thanked: 106 times
Been thanked: 520 times

Re: change individual bits in a byte

Post by mnfisher »

Hi Dirk,

I don't think there is a way to set on the value of a boolean other than using a if ... else ... (conditional)

There is a way to always read true or false (as 1 or 0 - note any non zero value is treated as true)

.set = ((.var & 0b100) != 0) // Where set is a boolean - will always be set to true (1) if bit 2 is set for example (or you can shift the result of the and right (using >> 2 in this case)- I'm not sure if there is a speed or space advantage to either approach)
Similarly .nset = ((.var & 0b100) == 0) // Sets .nset to true if the bit is 0

Martin

mnfisher
Valued Contributor
Posts: 1008
Joined: Wed Dec 09, 2020 9:37 pm
Has thanked: 106 times
Been thanked: 520 times

Re: change individual bits in a byte

Post by mnfisher »

Note that you can also set / clear multiple bits at once.

Post Reply