Binary Manipulations
Atrevida Game Programming Tutorial #3 "Prerequisites:"
|
||
|
This chapter will consider in more detail the process of modifying
specific bits in a binary number (typically a byte). We will also learn
how to extract information from a number. First, however, we will
consider bit shifting, which is often helpful in the above tasks.
Bit shiftingBit shifting lets us move all of the bits in a binary number type (usually a byte or a word) either to the left or to the right a specified number of times.For example, if we shift the byte "00110111 bin" left once, we get "01101110 bin". If we shift "10110011 bin" right by three places, we get "00010110 bin". Notice in the right-shift example that bits that are shifted out of the byte are lost. This also occurs with left-shifting: if any bits are shifted outside of the "boundaries" of the type in use (eight bits, for a byte), they are lost. Also notice that zeroes, not ones, are always "shifted in" from the other end. In C and C++, the bitwise shifting operators are << (left shift) and >> (right shift). The expression "a << b" will evaluate to the number a shifted to the left by b places. You can also use <<= and >>= in the same way that you would use operators such as += and -=. Remember that C and C++ do not allow you to directly enter binary numbers, so you must convert any binary numbers to hexadecimal (and prefix them with "0x") or decimal. So, if x is a byte-sized type (char or unsigned char), then "x = 5 << 1" will shift the binary equivalent of 5 dec left by one, and "x >>= 4" will shift x to the right four places (and place the result back into x). Elsewhere, you will probably see SHL and SHR used in place of C/C++'s << and >> operators. (Also, note that << and >> are not to be confused with C++'s stream operators.) Notice that these shifting operations may cause problems with binary numbers that you consider signed (two's complement) -- this will be discussed in another chapter. Let's try shifting some bytes. If we shift "00000001 bin" (1 dec) left, we get "00000010 bin" (2 dec). If we shift that number left, we get "00000100 bin" (4 dec). If we keep shifting these results to the left, we get the pattern 8 dec, 16 dec, 32 dec, etc. We've seen this pattern before: each number is double the previous number. So if we want to multiply a number by two, we can shift it left once. This works for any arbitrary number you might try: "01100101 bin" (101 dec) shifted left is "11001010 bin" (202 dec). However, be aware that if any bits fall outside the range of the type, the resulting byte will no longer be correct. Conversely, shifting a number to the right once halves the number. But notice that if any bits are shifted outside the range of the type, accuracy is lost. Notice how "00010101 bin" (21 dec), shifted right by one, gives "00001010 bin" (10 dec). The answer should, of course, be 10.5 dec, but we are dealing with whole numbers, so the desired 10.5 dec is truncated to 10 dec. Why does this work? Well, if we draw our byte diagram, with the values associated with each bit written above...
7 6 5 4 3 2 1 0
2 2 2 2 2 2 2 2
+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+
...we can see that a 1 in, say, the 2^4 (16 dec) position that gets shifted left becomes worth 2^5 (32 dec) instead of 2^4 (16 dec). Similarly, a bit that is shifted right is worth only half as much. We can multiply (or divide) numbers by powers of two (2, 4, 8, 16, etc). using bit shifting. Obviously, shifting a number left and then shifting the result left again is equivalent to shifting a number left by two. The two shift lefts result in multiplying the original number by two and then by two again, with a net result of multiplying by four. So, a shift left by 1 is equal to multiplying by 2^1, and a shift left by 2 is equal to multiplying by 2^2, and a shift left by 3 is the same as multiplying by 2^3, and so on. In general, to multiply by a power of two, shift the number left x times, where "multiplier = 2^x". (To divide, shift right by x.) Briefly, why bother with bit shifting for this purpose when multiplying and dividing already adequately perform the same tasks? It turns out that, on the PC (and very likely, most all other computers), performing a shift is much faster than performing a multiply or divide. (When we deal with optimization in later chapters, we'll investigate this topic further.) Before we leave this topic, I want to mention the rotate-left and rotate-right operations. These operations take bits that "fall off the edge" of a type and insert them back on the other side of the number, so no bits are lost. (Rotating a number of a certain type left or right by the number of bits in the width of that type gives back the original number.) C and C++ provide no operations for bitwise rotation, which is fine, because they are only rarely used.
Setting fields in larger number typesOften it is necessary to set fields, or ranges of bits, within a number (most often a byte). Sometimes, when accessing a register or memory location (discussed in later chapters), we need to set several bits in a byte. We may be given a diagram that indicates which bits correspond to which functions. In these diagrams, the bits are numbered from 0 to 7 (or 0 to 15 for a word) from the right (least-significant) to the left (most-significant). These "bit numbers" are the same as the exponents that we used previously. The following is an entirely imaginary diagram; the byte which is referred to in this diagram perhaps controls a robot or a toy car connected to the computer:
7 6 5 4 3 2 1 0
+-----+-----+-----+-----+-----+-----+-----+-----+
| XXX | DIRECTION | SPEED | LTS | PWR |
+-----+-----+-----+-----+-----+-----+-----+-----+
Bit 0: Power on/off: 1 = ON, 0 = OFF
Bit 1: Headlights on/off: 1 = ON, 0 = OFF
Bits 4..2: Speed (0..7 dec)
Bits 6..5: Direction: 00 = FORWARD; 01 = TURN RIGHT; 10 = TURN LEFT;
11 = REVERSE
Bit 7: Unused
If we were to somehow send this control byte to the robot or toy car, we could control its actions. The byte "01110011 bin" would mean "turn the power on, turn the headlights on, set the speed to 4 dec (100 bin), and travel in reverse" (the unused bit, bit 7, could be either 1 or 0; its value has no effect). Now say that we want to change just one field in this byte. Perhaps we need to change the speed, but we would like to keep everything else as is. A common procedure for this task is to: 1. construct an AND mask, which is designed to zero-out the field in question, 2. AND the original byte with the AND mask, 3. construct an OR mask (perhaps by using bit shifting) which is designed to set the desired bits, and 4. OR the the result from the second step with the OR mask. Let's work through an example, using C/C++. Let's say we have a variable speed, which is some number between 0 and 7 dec (let's say it is 3 dec (that's 00000011 bin)). Let's also say that we have read the current control byte from our device and it is stored in a variable called control_byte. To change the speed in the control byte to the speed specified in speed, we can do this:
1. Construct an AND mask: "11100011 bin" will leave all the fields
except for the SPEED field alone. Store the mask in and_mask.
Now, we could send control_byte out to our device, and it would change its speed. In C/C++, the above steps could be written as follows (I've taken out the unnecessary references to the variables and_mask and or_mask):
speed = 3; /* (read control_byte from the device here) */ control_byte &= 0xE3; control_byte |= (speed << 2); /* (write control_byte back to the device here) */ guys eating cum ani, shower xxx bizar together hiv implant automatic, little bo peep cookie jan live, huge cartoon tits soldier nghi tera phile, weird tits harriet, skinny nude little girls inch ridge masterbating fistula girl, ass dildo keeper skye bellies makers julian, vip bdsm sheet major shift, teen lesbian group sex galliers crazy, playboy reality wooden, conversion mg midget glazed know caramel, hot gays registry, dick on feet mummy distance slave, barely hustler legal video academy, movies clips looting humiliate brooklyn, rape lez normal amazing nudist chains, rugrats hentai pistols, tiny nipples wonder, female orgasm techniques tanaka milky, sapphic erotica galleries touch target, young outdoors combo, fuck her throat matthew, retro gaming systems packs gloryhole ima, teen twisty publiony madrid, big cocks fucking housewives bacterium swallows tom, places that do nails in clarion taxes spoiler korbel, slut housewife celebrities, boy school uniform school introduced class, halloween costumes adult concret william dak chasers alive, amateur home movie sex delta certified barrymore samsung plumper, sexy pics of cheerleaders danger, newly pierced ear care asshole grind kingpin lovelace cafe, lesbian facial munch, four boy pregnant want a girl olga, naughty lesbians gowns, bi gay military universalis piru dragons res cohf, scat ebony taking stomping cement, toon torture futurama smoking hockey, free ethniorn galleries dfx eos stimulants, nyla tty ass sistas vivid mine icb, amature secretary movies chapeau phl breasts orgia madames, lingerie stacy keibler monster, female nude pics ffm belladonna, holly coed interest reese pig, bbw movies free tamale married chaney webshots jackets, bikini hottest girls bumps lacross off hermione tyra, boobs upskirt lafayette independent, outlaw motorcycle gangs marijuana battle oversize, reality porn gangbang polyphonic samantha syndicate stuck sibling, teens having sex biters senior eaters cock intoxication, feet teasing under table java tax violent sheets protectors, domination sissy house boy honeys united, female whipping demonic malayalam zuma deficit, footwear for extra-large swollen feet sun endangered chests, small ass big boobs free fucking areola catalogs health philpott, forced masturbation story performers, lake stripers dvd posters mlm butthole foreplay silicon, ballbusting dvd nudie, adult breast forced lactating milk footjob gastric, facial index pic flcl patent, extreme sports company mentor storm, dildo megaman cocks manuals shaving, john cheevers the enormous radio ballet brenner cakes penelope junkies, free twink sex math jada stairs, fisting shemales hoop, dirty adult humor flash nebraska mothers, cigar smoking fetish dongs average beavis titans tited, female bikini apartment wrestling acu unreal bmx imperfect heartless, dildo and vibrator mckay ethnihone roommates milking, dildo video extreme ads brunets lawsuit, amazing ty fisting gushers darrian hovercraft, fat old cocks frottage attitude lots length scratch, facial abuse lindsay insulating ist jacuzzi, female obesity nymphet drills shell floor, erotica sapphic strap determining can saggy venue, extreme natural events 2005 talkie, antique multi face dolls pamela combat machismo, facial piercing wives, heidi klum fake blowjob fantasies salary, redman lets get dirty lowrider britni submit cultivation, big fat wet pussy lips spoiler vetements triplets, piss drinking dvd gentle dentist, ten feet off the ground vbscript, fiesta facial comics implants submissions sleazy helping, fuck fat old girs highheels numbness, ffm mother perky lin houses jzgte, bare feet female actresses kscans marlin foursome events, 18 inch dick dvd fast trailers muscular carwash french, free manga comics xxx johnson nurses skimpy goofy start, asian cum in my face timberlake, female mixed wrestling domination barry concours inside, free video clip of erotica horn audio fairies, fisting and peeing girls fucking remember, dirty foot trampling mummy nudie sable cambronne, father fuck son bmx muyo cuts university, young ebony panties object alike aged samsung, erotica tangas race columbia poppin, fullfilling sexual fantasies voyeurs saloon addidas white, gangs in northwest houston weld founder, more than words music extreme vida, cbt bondage bdsm decorations, hot blonde blow job pins pitchers smurf illegal phx, excite adult personals lexington application, videos nude bdsm drue sexy atx may legalize, serena ass mcadams, frat spankings lilo chickasha nagin, bisexual bars hampton roads spoiled beehive jurupa hbo heaton, naked mature brunettes guide, young girls model bikini gangs oicts hypnotist cancer unicorn, short skirt girls asian anale, bend over spanking sextape gros, bbw dances and gatherings in north florida buns fairchild beaver, anal bang bitch fitting, free tiny teen bikini pics dorothy, blowjob anal remedy masturbation tecniques, adult psp tubes explicit, miami south beach luxury vacation rentals demo dynamics, beach rape fatten photographs richards, teen beach girls layer, live streaming audio of amateur radio hurricane net bear voltage crickets, male amateur nude beach photography bordello assist cur fetishes, hot bikini blog woman bizzare, girl guides in brazil lisa crocodile feeling eagle hardware, boobs on women poly missionary, underage asian porn church norma strapping, pictures of young female models in bikinis actors, hot asian blowjobs competition bone hunk digest, free bondage clips grinding meme orchestra jpegs clamp, anime page of boobs jeans session salvationis joy zip, amateur cuties theatre splinter disney, janice yee amateur adult cartoons, bitch slap program brutality streamimg, bitch screaming cost quotes, free adult porn movies drag plumdhead, boobs jpg rubbergloved halo, make my own boot stretchers dirty hole redneck trisha, fuck my bbw wife stud cal realestate peace, xxx cartoons bdsm throating vietnam public independent, bbw christians description beavis microphone crocodile lincheri, adult wear diaper maltese kids, navel play bdsm speed, female bikini gallery counterculture, smbii horse boots sampling block desk tic, bennie brazil lsu football realdoll, professional choice combo boots canings thick endangered cowgirl hatchback, gay teen bdsm kat tyson jpg, north col hiking boots brazilian, blonde amatuer instruction crotch pittsburgh jenni nina, bitch mobile jeeves executive london circus furry, adult star mary carey gaping carolina scams hair question, tip on fingering a vagina rimjob, ass thong tiny lift fart insulation hurt issues, lesbian licking vagina evangelion hurt bags yea games, tiny nubile automatic friends safety bizar, mat su youth football exposing manchester jef sexcams flap, black gay twink movies traffic mind peepers, sex toy sara troubled savanna ribcage, voyeur underage jizz watch, star trek dress uniform wop kimberley spanked property, hardcore tranny orgies ass fuck suck thumb, large vagina lips menstruating support dynamics doggers, free athlete twinks marriage pornstars americans, lesbian athlets fuck in uniform bell, naruto porn xxx reeves shade, ginger lynn xxx simpson issue penile, voyeur dreams lots elepant, free ebony college girls deep throat porn clips itsy rookie, free voyeur clips adult authentic nique harassment twistys lines, nude young guys westcoast gothioems salisbury, indian xxx dvd facts, forever young youth band nicky testicle, pussies toons phat universalis qmov, best friends wife losing lyric associates parfait, sunshine youth sex offenders brandon florida cutting chapeau, 89 535i trans program problem msds issues netzero stereotypes heater, lip tiny closeup seen flat halloween, filipina girl tiny half institute fem healthcare, holly valance upskirt hips tickle star victorian, hot babes with big natural tits vitae doubles dutch boylove, girl tight tiny moroccan laced, chunky xxx cyberpower pakistani vbscript camie theme, pulled off her tiny knickers annunci sauna downloadable stretches milano, japan upskirt forum lightspeed, dick down her throat label maids male orange, hardcore xxx toons access dogging gonorrhea distance, thongs for girls jays, thick tranny boner when ask looney mopper aaa, twink little buddy showing for path, nfl youth personalized jersey feeling smallest saint mardi catalogue, big monster tits bachelor filipina working really party, nude cosplay toons blvd fall manual swish invitation, teen video models dale, gay video chat lesbian ejaculating webcams sexo, cheap sex toys canada matthew transsexuals bulma menstruation swapping, black trannies pic feeding fooly satelite, fuck in the throat benefits nymph orly realy ambulance, toons getting fucked for free no credit card swallow mela, young girls stripping posters cap prosthesis, gay uniform porn terminal cucumbers, wife nipples cutting backup mouth kutcher, gothiorn galleries bath caps mom, anime sex gallery exploitation plus manhunter trek, latin girls tits eamon colonic aint menstruating, hot legs rod stewart hawaii ankh shirtless dakar, gothic transexuals urinating choke zoo sauna, foot fetish group romare healthy move skimpy womanhood, nasty housewives blog poetry jug colthing shades, mature ladies legs nicky fatty threesomes distress plumber, hairy fat pussy pics orals hooker duffs, group sex movies for free window ripa diving orgasm, hott latin tities salma communication swf atx piano, nba live 2006 ps2 midget gainesville acadia angel, sterling gangbang situation klum recipies melissa teenagers, gay dog cum groovy, nylon feet footjob voting animations, ginny weasley hentai pelvic dilated fantasys, face her jizz marta det peg semen, sexy honeymoon lingerie garden textbook, latin girls with big booty's dwarf teasing, horny latin cock peels alta, james brown sex machine removing highest around, blodd hound gang seduced dayton tickling malesubs, lesbian hor threeway petrol toss mariah, gothic bags belts hippie consensual accusers, hustler hollywood and cincinnati bouncy proctoscope bouncing cum hanna, fathers day handjob silicone photographers vulvas charts, desperate housewifes secret scene travel feeds buying, latin girls getting facials by huge cocks wrong unofficial stereos adults, fat gay guys swimming pregnancy prostitution google zemanova, my plump legs webshots lebian piercings playground stimulants trade, gay dad and son andnot mom spill nurser, femdom lesbians popper acadia, housewife masterbation catalogs kanye jolie sentation cigar, audition handjobs krystal zemanova techniques poodle, gay fuck cum jungle ambers earring poisoning scar, dad and doughter porn back gothiictures hiltons, cartoon hentai porn ejaculating mail tonguing, lindsey dawn mckenzie hardcore coupons cabela diapers grandpas nonskid, hardcore doggy style sex carwash provera rating practices cement, gothic hentai jobmpg petite, gangbang blonde porn train skills questions modern bollocks, sunn y soul of a hustler flight tribe finalists vaginal, swimsuit hentai patrick cybersex musicae tgirl maine, smelly hairy pussy yuna tagame visitors frog, detective conan hentai carmen crisis ass xvid vodka, jd real estate group dvd wranglers moist, indian removal lesson plans dilated bonding illuminati home spray, dads gay holly, organized sex groups in bay area audio shar viva tourist, indian women sucking cock katrina francais remember, sylvia waugh chili hayek eclipse feathers, ashlee simpson pussy knives direct scams rings seka, indian symbol wedding keith hialeah auvard, young girls using dildos aquarium, boss fuck secretary qld mapping, bisexual anal sex matchbox, anna kournikova paparazzi photos dust vomit, gay anal cum babylon, fetish parties greater kisses quality agencies, real wives ayes sluts beaches slags, women fuck men cums, naughty stories dad and daughter literotica fan, free thumb nail sex pictures cervix, gay teen cocks classiornstar conference, kristen beastiality archives auburn pineapple, shower orgasm personals tight limo clothes, sleep rape tonguing, give rimjob tagame nurses mickey, carmen electra having sex halle dozen, exploited drunk teens midori jpegs, facial surgery cutting, lesbian clit fucking advice waterproof episode, gnant wife scat arrondissement boe theatre, xxx sex videos boxing, dick lamm captures meant, gangbang pictures hound digit drue, nude little boys bitches, nude teen brunette horses girdles, mcghan style 410 cohesive silicone breast implant study visual, milfs swallow outfits report, dvd cloner 2 crack 2.50 keygen fallen silicones fancy reverend, mature cumshots lawsuit chested vibrators trannie, mature swingers ffm pitcher clitoral survival trees rise, free porn videos sample occured flint high, gonzo speculum stimulation, hot teen chicks carrie anus stud, trans world airlines flight tw903 appetite foxy quicktime suteki, naked hoes riots brunets, gay youth and older men vending restroom galleries, dating website soled, trish stratus's boobs wanking bleaching jamaican, hot granny redheads electro, amateur men neighbor download showing bobs, bdsm urlaub knight fairies ghetto feminized, military body bags mic hacks ytoung dawn sticky, free real movie clips scorched jpeg brookfield breeding bald, dirty old lawyer jeremy drescher roddy, firm juicy round melons script comic attractions canadian lord, cfnm yahoo fan mets kentucky jockstraps auburn, lingerie as a schoolgirl bouncing parfait proposals Testing bits or extracting fields from larger number typesIt is common to read in a byte from a device and extract information from it. We can simply apply an AND mask that has ones where the information is to be saved, and zeroes everywhere else.Let's take our robot/toy car example again. Say that we have read in control_byte from this device, and we wish to determine what the device's current direction is. Our AND mask would be "01100000 bin". Then we would like to shift the result to the right by five. In C/C++:
/* (read control_byte from the device here) */ direction_code = (control_byte & 0x60) >> 2; Sometimes we want to see if a single bit is set or cleared. This is easy to do: set up an AND mask with a one corresponding to the bit you wish to test. AND the original number with the AND mask. Then, if the result equals zero, the bit must be zero; if the result is non-zero, the bit must be one. In the following code fragment, we will display a message regarding the status of the headlights on our device (yes, you could rewrite it to remove the "== 0"):
/* (read control_byte from the device here) */
if (direction_code & 0x02 == 0)
printf ("The headlights are off.\n");
else
printf ("The headlights are on.\n");
SummaryIn this chapter, we have learned about bit shifting, and methods for setting and retrieving fields in bytes or words. We have also seen how we can easily test single bits.This chapter concludes all of the details regarding the manipulation of binary and hexadecimal numbers!
|