delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1999/07/20/12:30:17

From: "Pavlos" <trash24379 AT usa DOT net>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: shifting left, and shifting right...
Date: Tue, 20 Jul 1999 05:20:18 +0300
Organization: An OTEnet S.A. customer
Lines: 58
Message-ID: <7n0mc8$382$1@newssrv.otenet.gr>
References: <37937D02 DOT 5D28D561 AT geocities DOT com>
NNTP-Posting-Host: dram-a11.otenet.gr
X-Trace: newssrv.otenet.gr 932437192 3330 195.167.113.234 (20 Jul 1999 02:19:52 GMT)
X-Complaints-To: abuse AT otenet DOT gr
NNTP-Posting-Date: 20 Jul 1999 02:19:52 GMT
X-Newsreader: Microsoft Outlook Express 4.72.3110.1
X-MimeOLE: Produced By Microsoft MimeOLE V4.72.3110.3
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

Sahab Yazdani wrote in message <37937D02 DOT 5D28D561 AT geocities DOT com>...
>I'm having some trouble understanding bit-wise operations.  Lets take a
>transparency map as an example, it would be more efficeint to store the
>transparency map as a pixel per bit bitmap (ie black and white), but I
>have no clue how to store the individual pixels in the map.  Somebody
>told be that I have to use the shift left and right operators << & >>??
>Can anybody confirm this and also possibly send some code as to how to
>do it???

Consider this byte:
0 0 0 0 1 0 0 0  <-only bit 3 is set
7 6 5 4 3 2 1 0

if you do the >> shift, it will become
0 0 0 0 0 1 0 0 which by the way is like dividing the byte with 2
and with <<
0 0 0 1 0 0 0 0        like multiplying with 2

There are lots of ways to set the bits to 1 or 0. Which is the best, depends
on what you want to do.
A simple way is this:

unsigned char b=2;
the bits will be:
0 0 0 0 0 0 1 0
7 6 5 4 3 2 1 0

To set bit 2, you do:  b|=4;  and the bits will be:
0 0 0 0 0 1 1 0
7 6 5 4 3 2 1 0

To set any bit (not only in bytes, in integers too) you follow this:
b|=(2 raised to the bit you want to set)
So, 4 in my example is actually 2^2. To set the bit 3, 2^3=8 --> b|=8;

You can set multiple bits at once like this:
b|= (4 | 8);    (set bit 2&3)

To clear a bit, you should use the & (AND) like this:
b=12;
0 0 0 0 1 1 0 0
7 6 5 4 3 2 1 0

b&=~8 will make b
0 0 0 0 0 1 0 0

What is the '~'? this make the '8' which is
0 0 0 0 1 0 0 0 to
1 1 1 1 0 1 1 1
So when you to the AND, it's like saying leave all the other bits as they
are and clear bit 3.

I hope this helps (and I haven't made a mistake :)

Pavlos



- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019