BitUtils.jl provides convenience functions for extracting and manipulating single bits of
integer variables. The LSB is bit nr 0. For completeness also bitvectors are supported. In
this case bit nr 0 is the last bit, indexed by ...[end]. I.e., after applying functions of
BitUtils.jl, bitstring(a) returns the same string regardless whether a is an
integer variable or a bitvector.
All functionality of BitUtils.jl can be achieved with the <<shift left and other bitwise
operators in Base. But by using functions code can be clearer and more readable.
For comparison, MATLAB has
bitset to set a bit at a
specific location.
The functions are:
-
setbit(b, T=UInt)returns a value of typeTwhere bit nrbis set, all other bits are zero. Equivalent toT(1) << 3andT(2)^b:setbit(3) --> 0x0000000000000008 setbit(3, Int8) --> 8
-
setbit(x, b)returns a copy ofx, but where bit nrbis set. All other bits are untouched:bitstring(setbit(UInt8(3), 4)) --> "00010011"
-
setbit!(x, b)sets bit nrbof the bitvectorxor the dereferencedx:x=Ref(3) --> Base.RefValue{Int64}(3) setbit!(x, 4) --> 19 x[] --> 19
Note that
y=3; setbit!(Ref(y), 4) --> 19
does not change the value of variable
y(more precisely, neither the value to whichyis bound, nor the binding ofy):y --> 3
Generally, Julia functions cannot change the values of scalar variables (except references).
-
bitset(x, b)returnstrueif bit nrbofxis set, otherwise false. -
setbits(b...),setbits(::Type{T}, b...),setbits(b, ::Type{T}=UInt)all return a value of typeT(defaultUInt) where bits nrb...or collectionbare set (and other bits are zero). For bitvectors usesetbits! -
setbits!(x, b...),setbits!(x, b)sets the bits nrb...inx. -
anybit(x, b),anybit(x, b...)returntrueif inxany of the bits nrb...is set, otherwisefalse.