Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change bit state in Julia

Tags:

julia

In Julia language how can one set, clear and reverse a single bit? I hope you won't consider this question out of scope or too broad; if so, please comment it instead of downvote it.

like image 759
Capitão Ahab Avatar asked Feb 08 '23 07:02

Capitão Ahab


2 Answers

Having this paragraph from Julia-Lang doc:

Currently, only sizes that are multiples of 8 bits are supported. Therefore, boolean values, although they really need just a single bit, cannot be declared to be any smaller than eight bits.

First it's possible to take a look at the binary representation of a variable like this:

julia> bits(Int(10)) 
"00000000000000000000000000001010"

and secondly, one can create byte value directly using its binary form:

julia> val=0b100
0x04

julia> typeof(val)
UInt8

and lastly, the best way to change value of a bit is performing right binary operation on its byte value:

julia> val | 0b10 # set 2nd bit
0x06

julia> bits(ans)
"00000110"

julia> val & 0b11111011 # clear 3nd bit
0x00
like image 139
Reza Afzalan Avatar answered Feb 16 '23 10:02

Reza Afzalan


I assume you are wanting to clear, set and check the states of specific bits in a byte.

Where:

  • N represents the integer in question and;
  • n is the number of the bit in question (i.e: the n-th bit) and;
  • the LSB is 1-th bit

  • set the n-th bit: N |= 2^(n-1)

  • clear the n-th bit: N &= ~(2^(n-1))

  • check the state of a bit by copying and shifting: (N >> (n-1)) & 1 != 0

  • check the state of a bit using a bit-mask: mask = 2^(n-1); N & mask != mask

  • reverse/toggle/invert the n-th bit, using XOR: N ⊻= 2^(n-1). The xor function may also be used.

like image 39
Tetralux Avatar answered Feb 16 '23 09:02

Tetralux