binary - what are bits and bitwise operations used for? -
can please explain, in simple, simple terms why need bitwise operators? started programming 1 month ago.
i understand stored in binary form. understand computers count in base 2. , understand bitwise operators. don't understand kind of programming require using bits , bitwise operators?
i tried answer on web, , read binary flags , disabilities, , got more confused.
i guess i'm wondering, kind of real life application require bits , bitwise operators?
you can pack data in concise format.
the smallest amount x86 computer can adress byte - that's 8 bits.
if application has 24 yes/no flags (bools), store them in 1 byte each? that's 24 bytes of data. if use bits, each byte contains 8 of bools - need 3 bytes 24 yes/no values:
> 1 byte per flag: > 0000 0000 = off > 0000 0001 = on > easy check: if(b == 0) { /* flag off */ } else if(b == 1) { /* flag on */ } > 1 bit per flag > 0011 1101 = flags 1, 4, 8, 16 , 32 on, flags 2, 64 , 128 off > packs 8 flags in 1 byte > harder check: > if( (b & 32) != 0) { /* flag 32 on */ }
this important network protocols , other systems every byte counts.
for general purpose business applications, there no need additional complexity, use 1 byte per flag.
this isn't used bools. example, applications may want store 2 numbers can go 0-15 - example commodore 64 needed conserve ram wherever possible. 1 byte can hold 2 of numbers:
> instead of interpreting 8 bits (ranging 1 128) > 2 4 bit numbers: > 1001 0110 > first number: 1001 = 1 + 8 = 9 > second number: 0110 = 2 + 4 = 6 > > getting first number requires bit shift move them position: > (b >> 4) turns above number this: > 0000 1001 - can cast byte , returns 9 > > second number requires "turn off" first 4 bits > use , operator this: b = (b & 15) > 15 in decimal 0000 1111 in binary. > > 1001 0110 , > 0000 1111 = > 0000 0110 > > once again, result can interpreted byte , results in number 6
one more neat trick check if number or odd. odd number has lowest significant bit (the 1 bit) set, while numer clear.
so check iseven looks this:
return (b & 1) == 0; // bit 1 not set - number
(note: depending on language, compilers may decide optimize stuff, in nutshell, that's it)
Comments
Post a Comment