cvs.gedasymbols.org/archives/browse.cgi   search  
Mail Archives: djgpp/1998/02/09/19:01:53

From: "John M. Aldrich" <fighteer AT cs DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Allegro ex11.c
Date: Mon, 09 Feb 1998 18:54:57 -0500
Organization: Two pounds of chaos and a pinch of salt.
Lines: 31
Message-ID: <34DF9751.1F0C@cs.com>
References: <34DF7294 DOT 21D0 AT home DOT com>
NNTP-Posting-Host: ppp212.cs.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Dan wrote:
> 
> i have a question concerning a part of the code from the allegro example
> files.  it's probably a stupid question but i've looked in my c and c++
> books and i can't find the answer.  here's the question, in this small
> snippet of the code..
> 
>       hotspot[c] += (random() & 7) - 3;
> 
> what does "random() & 7" do?  i'm figuring random() returns a random
> # of type int maybe?  but i have no idea what the "& 7" does.  the & 7
> is the only thing that i need an explenation for.  any help would be
> much appreciated.

& is a bitwise operator, along with ~, |, <<, >>, and ^.  It performs a
logical operation on the individual bits of an integral value.  & stands
for bitwise AND, so the above code causes the return value of random()
to be AND'ed with 7, which is 111 in binary.  The result is that the
return value has all bits except for the low three masked off (zeroed),
creating a value from 0 to 7.  The code then subtracts 3 from the value,
so hotspot[c] gets assigned a random number from -3 to 4.

Bitwise operators are covered in any standard C textbook.

-- 
---------------------------------------------------------------------
|      John M. Aldrich       | "Always listen to experts.  They'll  |
|       aka Fighteer I       | tell you what can't be done, and why.|
|   mailto:fighteer AT cs DOT com   | Then do it."                         |
| http://www.cs.com/fighteer/|                - Lazarus Long        |
---------------------------------------------------------------------

- Raw text -


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