Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

A, progriJ,mm';ng frangl)'age' is ,law level wh,B11 its

- -

programs require a', "lent/on to the irrelevant.

Previous t hapters ha e d, serib 'd I~ high-level m chi e-ind pend nr [e, ture ~ Aith ugh these _I. a ures are ad equate [tor many applic ationa son e pro, am' need ~. per orm oper:ation, t the brj[ t el. Bit manipuh ti n nd 'I her I" . -leveloperation are esp 'ciaIl useful fOT writing stern pre 211m (lncluding c ' 'j'L,r· nd eper ring systems , ,':0. ntlou pro" rams graphic -r'o,gramls and p,fll urn for which f'J II ·ecuU . ~ an, II r I, fflcie nil LJ', f space j.e C' 'iLi al,

Section ,~O,J ICO~, em Ie ~~ il:' j ~ - , IP 1', t r I' hi b pr, , ide' t

, dividual bit 1,'- ,d bit-tleld.i"'I etion ':'O~2 then sho ho

that cant in bit-tl lds, - inally '" {"[,'D -.0,.] describe h lure! t. p de liniticns union ~ :. nd pointer :) can 11 lp 'in writing ~('" =1 vel . rn-

I' 't'!IllIIn",

Ql __ l1li

Som I r Itil, t ehnique: J' db d in lhi ", 'h," pt! r uep nd on knowledge of how

" ,.18 i . t Ired in m, mory, 'fhL h C'~ n V' ry dep nding . m tb machin and the cornpiler, Rel- in,.' ,. n these t __ hnique will 'm '.' ,t.lila Jy 1l1Ue a program nonp rtabl ,~, ·,ll it' . b st to av j,d tber 1 unless ah I. Iut J~ necessr ry,. mf. au do n . ed them L~' to 1 lmit their u e 'to certain mr dule ~ in your pr ',~r.um· d '0 l '. '11 ad th 11111. ar und, And, 8 'O~ 'U b - aue to document what " OIJl re d im ~

- provid six ,bihl1i, ft' 10'1·FIl.I '1", ,which operate Ion inreg ,f data at the bir ! vel, We U discus 'the tw·, bitwise shif perator fir t, HO\\flcd b the f sur other bitwi e operators (bit" i e complement, bl wise and, bit, is .exclu i or ... and bitw lse inelusi e or).

Tabl.e 20~1 Bitwise Shlt) Operators

portability 't,ip

The bitwise sJtift operator can rransform lh -- binary representation of an integer by shiftingits bits to the left or ris ht, C provides tW'D- shift operators, which are' S,hO'WD in Table 210,,1.

~Jt,",lht)'I' Metlcl"ing

~< left shift

» righ shift

The operands for <,<: and >:> Inay be IOf aJ-~y integer type (including 'cha-r). The integer promotions are performed on both operands: the result has, the type of the left operand, artier promotion.

The value of i « j i tile result 'when the bits in i me shifted left by jl places.

For each bit that is "shifted off' the left lend of i a zero bit enters at the right, The value of i ~.> j is the result when i is shifted rlg'htl'j j places, If i is lot a,n unsigned type or if the' value of i i - nennegative, .lerlQ's are added at the left as needed, If i is a negative number; the result is Implementation-defined: some implementations add zeros at the left end" while others preserve the sign bit by adding ones.

For IJOruibiliry, it 's best to' IJ{t.rjD/~m "i7,itt~; lonly OR 't1it~~'~Rr1ed numbers.

The following examples ~llus,trate tbe effect of app~)dn..g the shill operators to 'the number ~ 3 .. , (For ~impHellty, these examples-s-and ethers in this ection=-use short integers- which are Itypic'laUy 16 bit .)

i' 13 /* ~ , 13 (binary 0000000000001101) *1
1 ::::::i ,', 1. 16 now
!
" " .2 I· .!!! · 5J2: I( b ina :r:y' 0000000000110100) */
::l . ~ 1 ,« . J .1S now
"
. ,i .2 /* · ; 3 (binary 00000000QOOOO011) ~I
:l = -1- >:> .. J 19 no'w
t As these examples show", neither operator modifies its operands. To modify a variable by shifting its, bits, we'd USia the compound asslgnment operator ~<= HDd

>~=:

i ~ 13; i «~ 2,; i »= 2;

1* • · .13 (binap:y 0000000000001101J *1
]. 1,6 n.ow
1* i -is rrow 5,2 lbinar:,f' 00000DQOOO110100) .. j
l* · · 13 (hin,ary 0000900000001101) *1
l. lS 'ntJiW The bitwise shift operators have lower precedence than the arithmetic operators, which cau cause surprises, For example, i « :2 + 1 mean .i« (.2 + ~)I" not Ci.«.2) +1.

"IJe 2; _ ,.-' .pern:tor

A. ~

eo. 1 ,Bitwis'e Operators' 5111

....

bitwi

Th - I P . rat r is unary: 'the inr ger pr motion are perfornu d .n Its operand. The other operator . binar: ~ the usual arithme tic' co rversion - re ~ erfc - D' 'd on th ir operand -.

The - ,~, &~ """" and ! operators perform, Bo 1_ n - perations nn all bit in their operands, The -- operator prl due.' the . cnn ,1,e'me'Dt of its ':p rand, with zeros repla: ed by I m s and Ol1~S T placed by eros, Thes, perator p' rf rrm 1:1 Boolean ant! - '_ ration on all ." 'rr esponding rit in L . t·. 0 prau I. Th . A , nd iper- tors

are simi Iar I( b tb ,-1<" rm ,3 "' II J . an or p_r,' . ion on tl.1" Ii 11 in their ope erandi ~,

hO\\L'VIJr!1 A produce 0 whene ' r b th -rand~ have a I bit, 'here.. I pronuces Ii

on 't ~ ~ nluse tho . bit» is, I' 0 .f· tor & od I ilh the logicu! ope f_,' rs && and r ~ ,~ TIt bitwis op - raters I,OIT1'C' imes pf . duce . he . am r, sults . _'" tbe J ogical open ._: but they re D t equivalent.

Th _ t!. llowing e "run oles i U u . rrate the I. ," '! - "'l . f the -. &~ "" ~ md opec _to ' :

unsigned short I j k ~.
1, I;
, "
i l*' t • 21 (,binary 0000000000010101) */
21 ,. 1 ],8 now
- I...J i
, 5,6, ." 1* j ~ 56 (binary 0000000000111000) itl
J' - l.S no'w'
,f
·k. , 1* k , - 655,l4 (hin,ary -l.1.11,11~~11LOll010 )1 */
=- ,...".~~ ~.s 'no
. ,
}e , & , I'*- k I now 116 (b:inary. oaOQOOOOOOQ10000) *1
- 1. J ~ 15
I
k i _~ /+ .k I 45 (bi.D,ary 0000000000101101) */
.;;;;, ] ill :La now
I
k i , l'it k ., 6'1 <'binary 0'0000000 OOll11,Ol j *1
c '1 ) ~ :LS, now
" The value shown for -i i- ba led OlD. th·. a' sumptioa that an unsLqnad ,9hor't 181u·_ oecupie 16, hit ...

The -- operat r ' eserves special rnentinnc sinc ' '.' e an use it to help make '> . D low-level program . m re porn 1_.. upp ,I:' tb_ t we nee an int g r hos bit are all L h pre ferred techniqu -1 ,I' vrite --o~ hich I . esa" d ~', Olin lh._ number ot bit in an irueee ~ .... irnilarly, 'if we need _ integer whc I - bit. I are all 1 exes p,~ fur the last five we. uld write -.ox~fj

C;,~, ~p-'f:.or' 2" 0 _ Ilia ~···I,~_ ..... ,'

A Lll

Each of the ,,...,,~ &t, A" and I opeeators has a, different precedence:

Highest: -

&;

Lowest

J\ ...,'~ bi b . ." ~ h '"

~ a result, we can CUDl .' ~ne t ,1e'S,!;! operetcrs Ul expressions without .. a;VU'lg to use

parenth .' e '. F,or exan ple, "we eoul d wri tie i & - j '~ k i nstead of I( i ,& (- j )) ~ k and i ~ j Ii, -,k instead of i, ~ {j & (~,k)) '. 0 f ceur e, it doesn I hu IT to use parentheses to avoid confusion,

if (status &- Ox,400 0 ~ ~ 0) .. n

Instead of testing whether at.at.us &, IQx,i~~O a a tsn t zero, this tatemen 'will evaluate IOx4 000 1 = 0 (which has the value 1)'1 then test whether the value IOf IS t.a tu s &: 1. i SD "1 t zero.

The compound assignment operat ",r. i&=, A = and I=:; corre: pond '10, the bitwise operaters s, A and ,I::

i ":2·1 /* .' j, 21 ~b.i,n~:ry 0000000000010101) *1
..... ' . J: 1.,B now
.j!
i 56 I~ j .. 56: ~h,i,nary 0000000000111000) I
J ~ '. l .. S now
"
i &= I /, i • 16 't bi nary 0.0>[;0000000,0100010 ) *1
1 ] ,~ ,,1, loS Dew'
,r
• A . /*- i .. 40 '~.biR,a,ry 00001000101001011000 ) */
l. - J 'il ~s now
I
. 1= . I . . 56 { ttin,axy OOOOOOOOOOl~lOOO} .J
i J • 4 r.s now
, U,sin':_' the- Bitwise Operators to Access Bits

When we do low-level plr ogramming , , we'll often need to store information ,8S, sing~"e bit: or collections of bits. In graphics programming, for example we may want to squeeze t\NOI lOT more pixel. into a ' ingle byte. Using the bitwise operators, we can extract or modify data that' s stored in it small number of bits,

Let's assume that i is a IfJ,..'bit 'unsigned shCfr~t variable. Let's fee how to perform the most common .'. ingle-bi t operation: .. · O'D i:

• SIl"liu,fl,Q bi'~ Suppo e that we 'WWIlt 0 set bit 4 of i. (We'~ U as urne that the leftmo -t-()if llJ'OI,' .r,ignUicdnt~h. i numbered 15 and the least s,'i'gnificanl 1t'\ numbered 0.) The easiest way to set bit 4 is to (Jlt the value of i 'with theconstant OxOO 10 (I "mask" that contains a ! bit in position 4J:

i = oxoooo~· i I: OXOO~01

l* i is n:ow ccsocoooooconono ,I 1* i is now DOODOODOU00100DD *'

More generally.if the position of the bit is stored in the variable j 'we can, u~')e a shift operator to create the mask:

i I ~ 1 '« j;

1* sets bit j */

_ 'or I,' amph ,-, if j ha til value ,- ,- then 1 <=< j, is Oxo 008.

• _" an, g 1- bf ~ Ii. CJIC. 'hil 4 L, W - d. usc a, mask with ~ 10 bit in po lti m ' :

and J j' I' _I", here else:

i = oxoa f j,'

., - a o~ f.\

1 &= -x "'u1:u;

/' i is ,now' OOOOIOO'001111111l */ 1 '. ~ is now 00000010011 Ol:lll .I

Using the IWlJ idea, W _ can c_ I, il write a " [at ement that clear a bj I h ~ po i" ~ ',n i - stored in "" ,adabl, ':

I' clea.rs bit j' I

if (i & Ox0010) ~

1* tests hit ~ *1

. [ ,·d - -. C' th ,(1: I] .,. ,- .,'" - t .. ; . .,. ,~

, " !I W - . . IU C 1- Ie l'OJ, . Wln a S. [em n ~

,

if (i &; 1 c< j) ....

I * tea ts; lJ_i' jl '* I

T I........ .I ..... c: .. ~I, Ii.. • • "1l"'1"O, ~, 11'1... ]

~om:a:~w.rJUng I~U'l:Jll,'le'.·I[er',·.' ortengr rnernn rnes. or ."runp ,

l UPPOSIC that we want bit'. O,~ J ~ and _ I(l 'II numb, r to xnre spend to the ·0101" blue" I reen and red.,re"p 'ell Jy~ First, we define names hat present th three hit p sitio - :

#,dlefine BLUE 1 'define GREEN 2 #define RED 4

Setting, clearing and te ting the BLUE bit, : uld be I' ne I .. folk ws:

i I;; BILOE:;'

.; & .. ~ _ 'BL"lrTI:I ,~

..iL, ,- _ -:=_il!..)"!:'!"

if (i & BLUED ~~,~

1* o~t~ B~L'r~ bLit' *1

!I:II~, 1_ g,. urQ.,..... I" .

1* cl!!ars BLUE bit wi I * tests BL'UE bit * J

t s also easy lit. J - BLUE' ! GREEN i

L 1&= ~ (BLUE I GREEN):

i'f (i & (B,LUE' I GREEN)) Wi

/* aet.s BLUE and GREEN lJ'its -- I 1 clears BLUE and GREEN hl-ts 'I 1* tea,'18 BLUE and GRE,EN Ol.ts, *1

D: . alin '. _ witb a group of "': veral c msecuti ,1. bi ".' I( a ,M';_fi . I'd) j_. . .. 1ighlJ. mor com ... ,

[icated than working with ingle bin ., H~ r . -' .. xamples of' he tw mostcommon

bit-field pera ion:

• 'odifyiR,g' a ,b,it-fleldll Modifying a bi -field require a bitwi: e and (to I clear the

bit-fiel .. ;; followed by __ bit, ise I I 't r- ", •. re new bin in the bit- eJI _l, 'i TIl follo ing sta emen 110W how we might I tl fie rhe binary value 101 in bit ~6 . f the ariabl , i:

LOWp>ILelfiel Programminlg

i ~ i L -OK0070 I OxOOSO;

I~ stores 201 in hits 4-6 ~I

The &; operator clear bits ~~6 of L: the ] operator then sets biL~ 6 ,and 4,~ Notice tho't i 1= OxO 0'510 ~y itself wouldn 't Ielw,I,y' , work. it would set 'bits 161 M,d 4 but not change bit 51 To generalize the example a little, let's assume [hat the variable j contains the value to be stored in bit .. 4--6 0 ' i. We"ll need to shift j into position before performing the bitwise or:

I ' ~ b~ 6 /

, Z ,stores J l;n-,,lt,s 4,- .', *- ','

The I operator has Iower precedence than &. and <: c, so 'we CI~U], drop the paren ... theses if we wish:

i ~ i , -DxOC70 I j cc 4;

.1 Re'tlielUJiiJIBtI' IJi, -fieltl .. When the bit-field is at the right end or a number (in the' 1lealignHican:L bits), fetching irs value is ,_,ElY., For example the following statement retrieves bits 10-2 In, me variable i ~

~- - ...., ~ - --

/~ retrieves bits 0-2 *1

I .: the bit-field isn't at the right end of of L, then we can first shift the bit-field to the end be-ore' extracting the f eld using the & operator, 'To extract bits 4r-6 of L, for example, WIB could use the following ratement:

j ~ (1 ~> 4) & axOD07;

One u' the simplest ways to encrypt , ,EUa is, 'to exclusive-cr (XOR) each character 'with a secret kc:y. Suppose that the key is the I" character; If we XOR this key wi' h tile character z. we'Il gel the \ character (assuming that we're using the ASCll_

ASCII cha'~,C1!ef set .Aprpen'(ji'K IE character set):

00'] 00 110 I(A,SCn code for &) XOR tl I ] 1 I UJD It As,ICn clade for z) 01.01 L too (AS,Cn code for \)

'To decrypt a me sag JI, w~ just apply th Slime algorithm. In other words by encrypting an already-encrypted message we' U recover the origi:n.aJ message, If we ,<OIR the & character with the \ character, for example wle~n get the o,rlgi!:lal character; ,2;;

001]00110 XOR atOll Ul!} 01lJ 1010'

(A,Sen code for &)

( AS' ·CU" " c ·o"d IV \ '\

,.... . ......•.. ,e lor ','

(,AS . _ code for z,

The following program, xor' .. C,~ encrypts fI, message by ":~'ORing each character '\yUh the' character, The, original rnes: ag_ can he entered b1y [be user or read from a tile using i-nput redirection. the encrypted message can be viewed on the i~pu~ andl tt~ltput Il\ltli'rectlon '''.22. ~ screen or sa ed in u Rile using output redirection, _~'or example .. suppose rrhat the.file

Trust not him witb your s,ecrets" - boll' 'when 1e - al,on,€ in your ro,O'm, turns, over your pta,pe' B ~

- ... Jo,hann Kasp,ar li'a-vater (1741-19011)

_O ' ncr- pt db - 'msg' fil " sa ing the I O_'_, pte ' m 1'_ : _Ie in ne'wm.sg~ ~",d use th

01[0 ing command:

newmsg - , ill'n',

lin, ' :

rTSttR BIR NOK QORN ~rST UCETCRO, 'N'I~, Q'NCH JC· GJIHC a,B 1ST TIIK, RSTHO IPCT l2ST VGVCTO --lIN,GHH utGUVGT jGP'GR(!T (,17'41-l8,Ol)

hi ,~h, ill displ ~ , ;' E -n the ~ ,ere, - D ~

. tbe exarnpie sbo .', our program -_ n. t chan .;_ sorn 'h_,_,~_·~t: r,' including digit i·ORin· these char _ t -", \ ith & would proeuce invi i,~ le control h uctcrs

_ hieh could. au-' preble D1 ' . ~ n ,1 me era ~ -',g. " '.' ' .. In I hapu r 2.2,. ~ll'· ,-

ho t., avoi pr blenu when 11. a Iing and . 'ri Ing file; th I '.' 'ont~ !n c nt.In~ char c-

ispr±n'L: iUWijctfDn .23.5 ters, U'ntiJ then, we U J I I,' it safe '~ u in I Lapr-d r t.uncU n to make SUl1 ' thatb th, the 'rileina1 cb· r: ter and th new (en"r pted) cb iracter are printin - ch r ... aeter (i.e.. n I. ntrc r eh l~aL:r r '. If . i h· r I.·hara·· t ~[ . ail" this t _ .. ,~ '! n ha- e the prog;ram writ - the oriainal ch ,- _ ter inste d ' the ne' characre ~

H r ~\, th' finishe - program, which j . re markab I , short:

xor» /w F'erforms XOR encrypticJn t:./

'e'include <c'type .,h~ ','include <stdio".h>

int main(void)

{

:tnt orig __ ohaz , ne-._char;

while I( (orig'_cha,r = ge1:crhar' ()) ,!::: E,OF) ( n.ew _ char = or'i9~ char A KEY;

if ,(isp<rint (orig~cha,r) && isprint (new_cha,r)) put chax (_l.'f!!W_ char) ;

else

putehar (oris_char)1 ;

}

}

Although the techniques of Seetion Ztl.l EIl.Uow ns [ I work with bit-fields these techniques can be tricky to US,e and porentially confusing, ' cortona~ely~ C provides 1[[1 alremative: declaring structures whose rnernbers represent bit ... fields.

As an example, let' Inok at how the MS~DOS, operating system (often just

(':i,~i' called DIOIS )'IDf1e's the date at which a file was, created or last modified. S"ince days.months and years are small numbers, storing thema: normal integer would waste space .. Instead, DOS allocates only 16 bits, for a date 'with 5 bits for the day, 4, bits- for the m.o th, ,and 7 bit" for 'the Ylcl.r:

~ T T I ~ I I ~ I[ t 1 T T
¥Iear: month day
I I I I j I I I I I I I JL___ I a.s 14 1], 12 a.i 111 9 8 7 6 5 4; 3 2 1 a

Using bit-fields, we ~'an define 1[1 C structure with an identical ],ayout:

SI'truc:t ,file ldat.e {

-=-

'uns.ign.ed int_ day: 5;

unsigned Lnt, 'm,an,th,: 4, ''Unsign~'d int year:: ? i

} ;

The number after eaehmember indicates its length in bit .. Since the memb rs all have j he' . Ifill! type, W.tC can condense the d eclaration if 'Wit want:

,~,truct file_..d,a1:e {

unsi'gned int. day~' .s I montih i 4 I Y"ear: ?; } ;

The type' of a bit-field must be' either Lnt; .. unsigned Lnt, or ,sign,eci int., Using Ln c js ambiguous; SOUle" compilers treat the field ~, high-order bit D~ a sign bit, but others don' ~LI'

e'i) In 'C99~ bit-fields may also 110· e type _,Baol", C9'91 compilers may allow ad;ditilun~d bit-field typles,~

We C"8n use a bit-field just Like , any other member of a structure, ,_x tble- foll,o,wingexample •... hows ~

rB·truct, f.ile dl,at.e fd;

f'dLO day = 21B i' f,d" month = 12;' fd '. year ....... 8 "

1* represents 1988 */

2'Q- 2·:

I ._"

I '.'.'.' 1111""

517

according to Microsoft). Artier these assignments, the f'ld variable will have the rOI~lowing appearanci :

[ I o~ r J
0 0 l I) 0 0 1 1 0 :0 :1 1 ~ 0 0
lS, l~ 13 12 11 10 9 8 "1 6 .5 ( J 2 l 0 'W- uld t~ -- d h bitwi . tors . jj' b th ff·-···· - •

.. '- . - , , ., .' - _., -, I .., I ,'., ,. , ,_. , "' • - - . I . . - I , . ,- - g. - _. _ _. , I {f

. . e CO[JI '. ave use I rne . I .. 1 ,f: operso,r.· to: accomp &, "same tt, ect; u-utg

these opera ton might even make the program a, little faster" However having a readable program is W ually more important than gaining a few micro" econds,

B,jt .. field do have one restriction tIl,at doesn' ap'ply tOI ,other members of at structure, SiJIICe bit-fields don't 'have addre se in the usual sense, C doesn't al1DW us to ,apply the address operator (&) to a bit .. field. Because Of 'this rule function, such as, ,13 canf can,' t store, data directly in a bit -field;

~ . ,- nf ( ~t ·.JQ..d" II if"~f-=- d' - d ._) '.

,6, o,a ,,-, "a . . ~ 1lIit,· '., I . a y, ~

10f course. we can alway' use acanf to read input into an ordinary variable and then assign it t'Q f d " day,

Let ,8, take ,3 close book at bow' a compiler processes [be declaration of I structure that has bii-field members. A,~ we 111 ee I the C standard allow'.' UlC c )m,pHer c nsliderable latitude in. choosing how i[ stores hit-field: ;!

The' rules concerning how th.t compiler handles bit-fields depend. lain the D,ObO,Jl of "storage units," The size of I. storage' unit ~ ... _ implementation-defined; typical value . are S bits, 16 bits, and 32 bn .. !~ As it processesa structure declaration, the compiler "acks bit-Iields one by one intu a storage unit. withno g,ops between the fields, UJ1~i1 there's no ~ enough room for the next f Jd. At that point, some compilers skip to rhe beginning of the' next storage unit. while others split the' bit-field ,aC'tO~ s the storage units. (Wlli.,ch one OCICU_· i imp lemen tation-defined.) The' order in. which bit-field are allocated (left to right or right '[0 1eft) is also implementa .... ti on-defined.

Our filE!_datle example assume I that storage unit, are J 6 bits long. fAn 8,bit storage unit would also b. acceptable, provided lb,~lll the campi ler s -Ilit tile mont.h field aeross two storage ILU1irt.) We also assume that bit-fields are allocated from right tn left (with the' first bit-field occupying the low ... order bits),

C allows us to omit the name of my bit-field. Unnamed bit-field" are useful a "padding to en ure '[bu't other bin fields are properly positioned. Cons ider the lim a sociated with I DOS file, which is tored in the following 'way:

st.rLtct file~c im'e { tmsign,ed iot seconds, ~ 5,~ uns i.qned int, minut.e,s = 6; una igned io,t, h,01.!lrs ,: S i

} ;

(Yon may be wondering how it" . possible to store the seccnds=-anumber between o and 551:-in ,0 field with only ,j bits. Well DOS, cheats: it divide . the number of second~_ by 2'0 the seconds, memb r is actually between 10 and 29,.,) If we're not interested in the aeconda field, we can lea\l'c out its name:

The remaining bit-fields win be aligned I~'- if the s,'8conds, neLd Were till present.

Another hick that WI!B can use to control the storage of bit-fields is to specify 0 as the length of an unnamed bit-field:

sit.ru.ct, s {

unsigned int a-::: 4,f! un.,s,ign.e,d int ~ 10; uns ign:ed. Lnt, 'b '~: '8 i

} ;

/* a-length h~t-field */

A O-Jen,gtb bit-field is, a signal to the compiler tOi .lign the following bit-field at the beginning of a ston . unit .. If storage unit are ,81 bits long, the compiler will allecate-4 bits, for the a, member, skip ,4 bits t "( the next torage UlW' 1 and 'Eben allocate ·8 bits, for b, If storage units are 16 bits, long, the compiler 'will allocate 4 bits for a, skip JI2 bit, and then all DC ate :8 bits for h,.

Some, of' ~I e language featuresthat we"ve covered in previous chapten woe used often in low-level programming, To wrap, up this chapter we'Il take a look ar several important examples: defining Itypes that represent units or > torage, u lng unions ~o pass normal type-checking, and using poimers as, addresses, We U also cover the vo 1 at i 1 e type qual ifier, which we avoided discussing in Section 18,.3\

_ .

because of itslow-level nature,

Delining Machlne-Dependem Types

S ' th h b d- JiI::, _,.:. • '. b w· .... e._' '~I ~ '1 ·

IUIce - 'Ie cr az tJpc-: y' ,~_y.nLl.0n_=-(Jc'CLllpte.' one " .Yt~ I_- omenmes trea

characters as bytes, using them to stan! data that s not neces: arily in cberaeter form. When 'we do sial I' It's ,3. gOOd idea to define I, BY'TE type:

D\epen,d-~[]g 011, the machine we may want rOI define ,I! ditional types, 'The x86uchitecmre makes e tensive use of 16, ... bit words so the following definition would be useful for that pla,lform,:

20.3 IOthl,sr Lowl ... Leve,1 Techniques 51191

ORD

- --"

"Il use the BYTH __ 11 -_ WORD ~ypel in I ter IX

Although union can e used in ." ponabl. ' ay----"-'e ' Section 16.4 fnr ampl ,S=--=the ~ - re I ",n U I in . - fOT anentiref diff-er _ n urp .:e: '1 _ ing blo - ' .. , m mcry in tw .' lor more diffei nt ways,

Here jmpb~: exampl 'I ed 10 the file da '_ e tru tur describer in

~

" :14:[, nOD -_1.2.. Since a - i 1 [e da t e stru tun ., W ,'Ie Ican think o

,EIDY rwo-bvte valu ':', a fille_date, stmcrure, In par ieular, ~e could . iew '-0 un,Slgn,eid s,hor.t ralu a _- f i.Le dat.e strncn e Iassumin that hort in-

-

glIB are 16 bit ~ ng)~tJe follo iog union allows U~I '101 easily convert a ' lort inte-

,,' e - to a fill' date or : ic 'er, 'I:

'uni on in t_d"aJ: e { u·nsl.gned short i; ~rtruc::t f Ll.e dat e fd; } ,J

With the b Jp of this, union, w e cou ld '. ch a file. d j t from disk as tWIQ bytes, heD e -. act i~'[ month; day, and ye,ar fi,. -']d~,,' '., .nvle~-· ~ J. w . -' 'Illid - ' . tru, I' dat, '

'i 1 e__ da t e' truetur /' I then ' rite j t Ito di sk .- pair I.' f b ' tes,

A '. ample of how we might use the int ~date unic n, here', hwC'''OD

llbl t, ~. hen pa . -d an uns i.qned short ar unu n- - rinn i! '- ,I a file d t =

void p'rint~datle (unsigned ahon n)

(

union int date u ,

u.,i ; or,

printf'(I!I%d/'d/'ld\n~ll. u,~fd"m.anth" u_fd..,day', u.fd.¥ear + 1980);

}

Using unions to allow multipl,e' view' ofdata j, especially useful when wo king with r ,o-i ters, which a ·'1 t, n ,U- i, . dint sm Ier uni COl .! '. P(I" , ors ~. r e tample have J 6-b'1 T~ gi .. ten named AX., B '"-'I ex. J and D, . '" -/ . b of th tse , .. ' gl . 1-' ters can be reated '. t 0 ",-i re is ers, '_' ,- I ~ . Jt:,' pl i divi~ 'le'~1 ill" regi tier named -Hand, 1(~h-HandL~tl:_nd,r "hiah n - "lo ,',~

~

Wh,:_n writin 10 .. -level appli_atil 11; -. rB6,.,,-~. 'led c. rnputer "1 w m' __ y n __ d

v I bl' th·, t repre en_ the contents of the A' '" HI, an, D[: !i j [ 'I ... __ -I.'

w- nt acce - to botb tb_ 16- 3J1d .·-bi reg!' ter ':~ lit 1:1 e

their rei -: i [ n hip [ Inl. ~I 'oU' t ( Ch··'D'- ',M in

AM or modifie AX I. hie nlution is t _·1 up two stmcture ,- , 0 'C c ~ 'oraiDin,8 me b r that I 1': -bit regl ste '~I and (he other cents inin:~ memb rs

that m'at_-'h the .. bit rezi ,IEf,. e then crea I , union - -' 1 '0 1'1_' the r- o strnc-

tur ·

- - - I :._ •

una.on. {

struct: {

WORD ,ax, bx, ex, dx~' } word,;

s,truct {

B'Sf"TE al,f' ab., bI-" bh., c I , ch, d'l , dh j } byte;

} 'reSt'S;

The' member 'of the wo rd trueture 'will be overlaid with the members of the byte structure: for example, ax will occupy the same memory as al and. ah. And that, of course, i exactly 'what we wanted, Here's am example showing how the regis union might be used:

regs ,~ by tie .' an ~ Ox12; re:gs .,byt.e .. al = Q,x34;

,print! ( u,AX: %.hx\n iii; regIs. w'()rd .. ax) ;'

Changing ah. and a l. affects a.x, ~O the output will be AX: 1234

Note that the byt.e structure lists ,al before a~eveD though the Al, reg] rer i· the 'low" half of AX and AH is III !;~high ~ half, Here's the reason, Wb,en a data item consists of more than O,De byLe;o there are tw logical 'Nays to < tore it in rnem ... 0:- y: wi th the byte in the "natural" order (with the leftmost byte stored fir! ,t) or 'with the bytes in revere rder (the left nost byte i 'tared la ".1). The fir-,t alternative i- called b~r ... endian; tbe second. is . 'own 8'-, little'-, IJldittnj ie doesn't require a specific byte ordering" inee that depends on the CplU on which ,8. pIvgram "wi t be execued. SODle CPUs u e 'the' blg- Indian approach and some use the little-endian approach, Wh,~u does Litis have to do witb the byte structure? It turn out that .x1S6 processors la· sume that data is toted ill liule-endian order, so the first byte' of r'egs iO wo·rd ,i ax is the low byt~.

We don't normally need to ',~orry about byte ordering.Hows ver, programs that Ideal with. memory aJ: U ]OiW level must be aware 'of the ord, r In whic ~ b)rleS are

'II tr . d (. th ..... ' .-., - ~ ,a -. - ,'l- il' j '. 1· 'il' s) It' -1' '. ' -,~, II. . -c, t '. he - orki . " . ,~ tl fil'- , 'il

s,ore· I as ~_ e I:eg,s exarnpie usrratesi, ~I aiso rei van w, en w .ILUng Wh_],1 _ res

tbal contain non ... character data"

Die careful when using unions to provide multiple views of data, Data that is valid in its original forma' may be invalid 'W'h_D viewed ID- a different type, cau ing unexpected problems,

W· saw lin Section II ,~lli that a pointer is! really sorne kind of memory addre s,

- .

although we usually dOD.'1 need to know the details, - hen we Ida low-level pro-

gramming, however, the details matter;

An addre's's IOfiOD_ bas, the san'l€! number ot bi t la' an in teger (01[ long in teger), Creating ill pointer that represents a ~ pecific addres j. _ asy: we ju ;~t cast an integer into a pointer; For example, here's how' we might tore [he addle, lODe I hex) in ,I, pointer variable:

BY'TE *p;

p ~ {BYTE 'It) Ox"lOOO f

/* p centains address OxlODO ~I

Our Dc xt prolgram allows the user to vi _ w segments of computer memory: it relies on C's wllllugne, '" to allow an integer to be used as a pointer, MO.sl 1- PUs, execute programs 'in "protected mode," however' which means that a program can aeces O""(y those portions ofmern :ry that belong ro the program. This prevents a program trom ~'ce sing (or changing) memory thai betong I n another application "f' tn the operating <y-'he'ill, itself As a result'! wle,'IJ oWy be able to use our program to view areas of memory that have been allocated for use by the program itself. Going out ide thes e regions will cause the p:roBT,mJ to crash,

The vie,wmemory OJ C program begins by displaying the address ,t f in own rna in fu notion a'M well as t r e address, of oaeof its variables, This will giV11! the WI r a clue as to which mew of memory can be, probed. Theprogrnm next prompts tile user to enter an address 'On the form of a hexadeci mal int_ ger) plus the numher of byu~~. 'to view. The program then dis, Iay a, bl . _ k J byte of U1C chosen length,

- -

'lllrling a.l the specified address,

Bytes are displayed in group of ,f 01 (except tor tbe last g~roullJ" hieh nla_ have fewerthan lO bytes), The address of ~ _ group' f by ties i ' die played. at the beginning of a line, followed by the bytes in the group (displayed a, hexade .... irnal numbers); fo,Uo,w,ed by the same byte ~ displayed as character I (just in ease the by es happen to represent characters, as some of them may), Only printing characters (a8 determined by the i,sprint function) will be displayed: other characters will be shown a, period I .,.

We"U assume that' int values are stored using 3.2 bit and that addresses are al 0 .32 bits long, Addresses " re displayed i'n hexadecimal, a .. IS IJtl nmary,

~ - - .

VI,sw:mISm'Q,r)tc 1* Allows the us.er 1:0 viey~' regions of COlllput:ler m~mOl'j' */

'include. ,cctyp,e .h~

~i.p,clude <E'tdiol ... h>

typedef unsigned caaz -BTIE,;

int main ('void)

,{

un.s i'~;p::uS!,-d, int addr : lnt i, n ,

BYTE *ptr;

print. f (n'Addrle,~s of maLO :funet.ion: i:x\n II ~ (unsign,ed int] main): printr(nlAddresm of aadr va:riable;: tx\nUr (uDs;'gn-ed int:~ &.a.ddrl;'

printf I( II \nEnt,t?r a (nelx), addr,elSS:: ~[)I; seanf I( II tx~. &acld.rJ';

printf (nEnter n lTliber OIf bytl8,s to vte- ~ 1111): s eanf ~ u %d[I[1 ~ &n,:

print.f ( 'I \n II) ;

print - (,n . ddres,s Bytes

p. r· - '~n·.· . t f ( .~ - _- - _- . - -

~. - ---------------------------=-

ehar,ac't'ers\n'll!) ; --~-~-- -- - \n'l[I[) I'

p ~ :iii:' (BYTE *1 ad.dr;

for (, n ~ 0; n -= 10) { prin't,,~- (11 ~,BX [iii I (unsigned

fo (i ~ 0; i c ~O && i c printf(ut .. 2X II~ *(p1:r +

for I; 1 ~ 1m; t+.)

p int.f I( II II ), ;

pr i 'f 'II II);

fer (1 ~ 0; ! ~ 10 && i c n; i++) { BYTE ch - * (ptr • ");'

if (isp~in_(ch»

ch.'~ m. I ;

pr in t.f ( [' %c II t' ch)l;

iIlt) ·pt.r) i I, i++)

i) ) ;

}

printf [{ II \11111) "

ptr +.= 10;

)

}

The program is c' m'pli,~':a,'ed somewhat bythe possibility that the 'v,· lue of n isn t a mul ipleof tO' S,D there m ~ y;I:' r - Jan L byte in the las " I.' p. . .. '0 of

the foz statements ar _ controlled b the conditie n i < 10 &,& i <: n Thi condi-

,

ti ill C U' e. the loop: '0 execut 110 time's or n time -hl[;) , .. If .. .... allen The r'\

also for-,. I'· nt th t (:1 mpen ates for any missing by~e' ~D full! It group -

displaying threespac s ror ea ]1 mi ~ 10' I yte," Th .. t way I :~b I , . ters that follow

be la I ,: .-'[ [P,t byt ' -, in alien preperly i' 'h 'tb ~ eh

II ", ,~ln,e· •

Th %X con e· .. -,i ms re j . I r used in thls progra 'i r similar _0' %c:'~- . hi h di .. uss d in Section 1,£ I., Th . difference i' that %X di: plays the hexadecimal dl its

B .. D _ and - "., upper- Ietten . %x di .pl,uy , them in lower cas .'

Here ~ whe happen wh ,n I compiled tile program usi 'g 'GCe and [1,_ sted it 0, an )t:8,6yst .. m runnlng Linu :

J

;;

Address o-f mal.n function: a04847c Addr1ess ,of ·,ddr v,sriable: b,ff411S4

Enter a (hex) address: 8048000 Ent.er number ,ot b,yte,B t.o ¥ilew·: 40

Ad{iress: Bytes'
_,_ __ I_~I- ,- - _~"!!!!!IIi!l!!!!!!!!!! - -- ... - ... - -- __ ......_:::J::II:...-'-" ......... ~.=.. _ r-- -=- ~~
B,O[ .acoo '7F' ,4·5 4C 410 01 011 01 [00 00 [HJI
,8 o 4: ,B, 10 I~JA, 00 ,00 0-0 0,0 100 00 0,2 100 03 0<0
.
,8,0'4B014 01 00 001 0,0 C'Q B,] ,():;4 018 34 100
8 QI49 [01.E 00 00 CO DA. DO on 00 Or C]I aD 00 i1',,, 3

~IU'~'~·

I asked the' program to display 40, bytBs starting at ftld.dreSIS' 8048000. whiiCh precedes the address of the ma Ln function. Note the '7F byte followed b:y bytes, representlng the letters E, L "and R, ' hese four ~)rt,es identify the fermat (ELF) in wblcb the executable file 'was stored. ELF (Executable and Linking Format) is 'wide]y used by UNO" systems, including Lin u x, 8048000 is full!' default address at which

- -

E 'ex,ecotabJes are loaded on x8ti platforms,

t's run the progrmtn again.this time displayin,g a blo ~'k: of bytes, that starts at the address of the addr variable:

AddreB,s of 'main ,funct:ion-~ '8,048470 Addres,,s of addr' ~v,a.riab,le: bfec5484

Ent'er a (hex) addre,e,,9: bfec:S4-B4 BJltle'J: number e,f bytes to view',:: ,64

.B,P'BC's',4 S'4 BFiECS,4 a,E 'BFEC 5,4,9.:8 B F'BIIC 5 ,411..2. BF':g"~5'4AC BF;EC54B6

B.FE'CS4C,O

a,4 54, B:C 'SF B,IOS4 Be BF F4 of 68 DC ]4 55 BC BF CO 54 EC BF 08: S5 B:e SF 'E] 3D 51 010 001 00 00 00 AD Be 55 00 08 55 EC BF El 3D 57 00 01 DO DO 00 34 55 E'C BF 3>C 55 'EM: SF 516 11 55 on F4 6F ,6'S 00'

!IIT"1l ill i!T"1i II!!lJO

h . 4U." T."

.. U ,. iil • :'W '. ~ .,

~U' f"'1i

~ ~ ~ ~ . ~ .~: ~I ~

~ -=W., . ~ .. 4 U ' .. , <u.~ V . U ~ .oh~

None of the data stored ill this region of memory is, in character form, I so it" . a bit hard ttl' fo']] lOW,., However, we do know one thing: the addx variable occupies the first ~our bytes of lhi .'. region. When reversed, these byte I form the number BFE,C54'S:4", the ~ld,dre:~s entered by the u er, Why the reversal? Becau se 1<86 proceSS()JS store data in little-endian order. as we'8W earlier in, this section.

IOn' ome computers, certain memory location ITe .ifi'Volla~iJe' ILhe value IO'red at such a Ioeation can change as a program is running, even though the program itself isn't storing new' values there, Far examplcc sornc memory Iocetlons might bl~d data coming directly from input devices,

The Valla t.i.le typ._ qualifier 'allow~ u· '[01 in orm the compiler :~r any 0 - the data used illl a program L~ v atile, vola't,il,e typical~y appears in the I' eclaration of a poinn r variable 'ttbar win point to ,ii) volatile memory localion;.

'volatile BYTE *pl;;

To see wily v'ola'ti.l,e is needed, suppose that p points to a memory locaticn tha contains the most recent Icbanlc'®er typed 8Jt the user's k.eyboard. This, ~OCatlIOO is volatile: its value changes each time, the user enters a character; . e might use the following loop 0 obtain characters from the keyboard and store them in a buffer

..... lifr"If"I'\J·· .U:WJJ:.I - J" iii,

wh i 1 e (bftltf!'J' II''O,/ull) { "ail' j~ r inpuT; bu.ffer[i] ~ *p;

i":' (buffer [i++] - - ~ \n II , 'break;

}

': phls 'i, .: ' ·d . " IIIlpi1.J : ight no .ice that this loop change '. neither Pi nor *p . it

could optimize th ~ progr m by alrcrinz i so that ·Pl ls fetch ' .. justonce:

. '£Ire ' Pi in: u ,. -'l~'i t rt while 'bt([fej I~'(J'I foil) { u ai! pJr' input i

buffer [i] c:= t aiue ~ ',()f d In res! r ,f; i (buffer[i, J == I\n~)

break;

}

Th i optirnlzed program ill fill the bu fer itb nu copi f th ~ ame char, , 'ter-c-not exae t[y~~hil we bad in mind. D claring that :p points 'to volatile data 1- 'oid~ thi, pr ' ble m Ily ~ Iling lh ' ce mpil r 'til _ *p m . b fetched · ~ ., m mi. -

t!." ~ ~ d

eaCILl nm • ~" nee I .•

Q~'



'. ,b "_. ,do ,'U D'I 1 b, ", in: & _.' I o· _ rat e imes plrodu e

tho ' ,. I I the && and I I~ op rater but Do,t 1&1-, . ,ii Ip'i1511]

-Oln _ ' I and I I &' '

i CI. j have 111 alue I or 1 n n any rnbim ion ~I Ith ': t ; XPI'"I I'. ion. rill ha e

the arne ahie .. H 'WV', r~ if i and j, h uld h, oth f'VWU' ''I th ,. 're·,"·, ns Ina~ not alwa ,S match. I' i is II ' nd j ~ 2~, '~,' . campl '.1 tbl n i '& j hot ..... th -, al De I i and j have no corresponding 1 bits), while i && j bias the' alue 1,. If i W' 3 and j: i 2~, then l_ & j h th ~ a11JJ~l 2 -, hil i && j h - the - alne 1.

'i -" e - cts ,31][ ther difference, valuating ~ & j++ alu'QJ1mcr,rne'D'tl. ]

. i :-1: effect, ·.'b· H, .. ' valuatin . i &:& j ++ ,0"1' tim '. iner m. mrs j ..

r. '"

. _ 'Ii

; . th most p , ,e'~' I -r th- reare . till pL ntv of files cr .. ated vear H, ',I

whose date arc tored in th DOS format. rn ,any event, D,OI fil dates 31'. ,a'~'ood flo,' bit-Ilelc are us' d.

IQ .... ··'I!

.',

_I do the l_ 'VII Ii'bir· - ndi. ., . d . lit J _"le:D.~ ~'_. __ "com,' fr,olD'ii [p, ,~ :Z101]

In J mathan " .. , ,iff noi 1 Gull';' er 'e . ravels. the fi crionul islands . '" Lilliput and

H lefuseu ar, p rp - tuall y at ud(ls €}'ver . heihe = t .01' n boiled eggs on ih ' bj.~ I nd 01'" tll - l~ end, I 'b . h -'I _ e is ru " i 'f _-- I' ,J . urse, ju t lik_ . he rde r t ., te in a

data item,

$1. I, how the oUqJUI p~odu_-_ d by each of tb followia program fr,a' rnents, A LlO1e rebal L, j ~ and k are unsigned ahor t; variabl ..

(3) i :. a, i j = .9;

p.rintf ( III %:"d~'" i ,,:> 1 + j » lJ ;, (b i ~ 1.;

'printf ( u %ldIM1, - & ..... i);

(c) i = 2; j = 1;, k - Q; printf ( II %d"'!, -i &; j A k) ;

(d) 1. == 7; j = 8;' k = 9 ,;

pr 1 n t f { II %d lit r • ~ j & kJ ;

2,. D I .. ribe D simple ~. - [0 "toggle' a bit U;hW1t' iL r m . t I r ~m'l In t fl I m lllnsm til

'~I hniqu ~ ~ ~,~, dting It tement thal 'tu - gle bi -4 td the variable L

~3- J plain ~ hat e feet the following 1m1 'ro has. un H" arguments. -~nu may assume that the

_or· LJm nt hBL' e the i: arne L_ pe,

#d,efine M (x,~ yl I( (xli -'= ty) , (y) -= (xl If I(X) =- (y) )

4;t 1n computer graphic '. ,Ot1 r: ar Of~'f.Hl stored as U1J,ee numbers, repre ' nting red, gte n, 811d blue intensitiea. Suppo se lbaL e,ach number require: eight bi ' '~ and we d like to . Lore all three val ue in _I single I [Ie int :ger~ .. rit a rna, r r arne MK ~ CQLQR wi LI1 'three parameter: the red~;gr n, and 11 lot nsities t MK _ C'OLO,R httld r turn u 10,ng in lucb II he Iia [ three b t -.. nt,i in dl 're .. 'en, and blu int nsiti ' .with the red '\ alu .... lb~ I~ I t b ~ - ,- Ild the sre J] value as th n '. t-to .. I S,' byt .

s. W~ iae macros named G,ET REDI, ,GETGR'EEN. and GET BLUE th. when gh eu a color ij'i' an rgumeru (s ,Jem'ke41. return i ,S-bir red gr. n, and rlu hu-n ities,

6. ()',C the bit, ise p l~.iLor; IU writ th - follo ying function: unsigned. short swa.p_byt1es (u~DsigD@d sholrt i' i

swap'_ bytes sh. uld return the GUill ber ilial result f om swappin the tw'on te 1 n i.

Short integer: OCCu.r. l:\VI byte· .t~ mo L compute rs, -or I.. ample if i h _" the value Olx,1234 (0 '0101101 I ·1 HJ1.0U 'in inar .. then swap_Dytl@S ~ 'b uld return Ox3412 t( IJ ~IOII 01 1 ~I· I~O jen binaryl, ll' .1' urIunction b~ writing a pr gram ibat re id a J1LUl1'" be r ~D _he~-adecl'ma1" lb [I wrin -I ~h number s ith i,t byte . wapped:

Enter a hexadecimal nueer (up co' .fo'ur d.ig'its): 1234:

Number wi:th bytes s'W'apped: 3412

Hint: se the %hx zon zersion to If· ad and write, th ~ h, x nu nbers,

1. W rite mbe t~oU~)rwing, functions:

uTI,sJ..gned int ro·t.ate_lef - (-Wlsigne,d Lnt, i ~ int n) ,; unsi.gnfld int ro~a .. e_right(un,signed int L, int n};·

t.atal,e left h uld I turn b~ ]. ul 0 ~ shiftin me hits in i ILO th ' 1 it . y n places, with ~h.'e bits that w e "shifted OJ!r' 11110'\led t 'the II iah end of i. Of example ~ the "all

526 Chap;ter ,201 ,Low-,Level P~cgram'ming

rot,r:rte left (Ox12'34 5,67,8 ~ 4) :h' ,"uld return 10>:2345\57 B,1 if inte " " ,- _ 32 hi I

"""""

1 ng.) ra' -a,te~r'ight j similar, but it sh uld ~ "~_t_' bits I ' the right in,_ mad -~ th - I t,

I-

I" Jill!

L -f ,- be the followin J.rnCli n:

int. f (unsignled inc i I

, n'\

~nt ,



arr m,

una igne d

{

}

n). i

(a) Whn" i ' he valu 0 I' - (-01 -c-c n)" I' Wh,at d e -~ thi ", function do ..

~_ i~e the rou~ - lng fun ~fiOD:

in't COiUDt __ one s (unsigned ,char ch); count one s ,h - uld return lb number of L bit in ch, (b) Write the function in part (a) wi~th~rut using a loop ..

10" -, rite - e ., n wing function:

unsigned int r,eve,rse_bits(-uns±'gnM, int n) ,;'

rev,er,se_bits,hu]d r tum an unsigned integer _' bit -, the ame -, those m n

hut "1 n Ii"aUilIii..r erder

IlJ I [I, ~ ''I i~,11 ..' . ~I. III

] L E· - b I[] "the f -Uuwi:QC macn i defin - tlu P ,-i ion fa' ~n', Ie 'lit i hln #,defin'e SHIFT BIT 1

idef tne 'CTR_L BIT ,2

-

#defin,e ALT BIT -4

The un, in,g st 11, nn nl: 'uPP _ 'ed to' be~ t wheth _ any. r th ' 1m - bit have been iet, bu I

D_- - , r I i ,; I IY' nbc' pecified messa " ~ I --~hUD wby the'. l.temeo'( _ e. ,rf on',· n sh

bow to fix it,. ASGLUDt! that key_code j, ID int variable,

i~:c (key_code &: (S-H FT_BIT III CTRL~BI'T' I ALT_,BIT) =,.= 0) print - (IINo, lllodifi,t:!I k,eys pressed\n~');

The 'followinD .unc ti on uppose Il' - omblne n 0 -_- res to " ___- unsi ned hort mteg r,

Expl inr why LDe fume ~ on doesn't W':' rk and - bow bow lOI.6-, i t,

unsi~eld short ~r,e,ate_ slhor.t (un5igne1d char high_byt@~ unaLqned char 10' _byte')

{ }

*1- _I

I,

If n i an unsigned an variabl wbat Beet de', the it I in n?

n '&:= n "'" 1;

,Hiflr.~ 1- .1:- nsi - er the e fee t '11 n i -

I. ~: I~ n I tDI' d ccerding t tb- . _ flea on .... poin' , tandnrd, a floa'_ alue cen sists of- J~

bit sign {the ]eftmp l-01i mos. si,,gnifi,ea.t1,t-bit}, n 8, .. bi'L exporu nt and it -'3~bit fraction, ,~n '(.hal O.rd f. I, sign a mictnre l)"p . 'th . oc upies 32 bits. witl1 bit-field eueen-I er corresponding 'to '[he lgn .. leo-n iI ,md fraction. Die lare tb bit-fi ld t ha ~, yp' Ulleigne,d i nt. Check th manual for your cumpiler to determine the order of the blt-fiek '.

PrtJf}'famming Projects' ,5:27

,*. ] ,5 . (a) As, ume that the varia ble s hasbeen ,declaffiied as .follows:: ,struct. ,{

intflag ,:' 1 $'

}- 8;

With some compilers, executingthe fDU,BWinJ~ statem,ellt causes lito 'be di·,· pJ,ayed. but with other com'p,i~ers,- the output is - I,. Expllainl the reason for this bebavior,

s ,. tla,'9 = 1;

pri'ntf (' %',d\n~~~, ,511. ~f'l,ag) ;

(b) Howcan tills pnJb],em beavoided?

] 6., S,llr_rtingwi'm the ,386 pro ce ssor, x;8'01 ICP'UI, have 32~bi't registers named Ef\X" EBX", ECX1, and ·BDX,. The second half (:the llea.5'l sigDlfiCaJ1[ bits,) of theseregisters "is the same-as AX, BX, ex" and DX, respectively, Modify the re'g:s unionQ' that it includes these registers tIS well as the older ones.Your union should be 'set up ~O' tb:31nl1udif-yjng 'SAX chm1ges-AX_larmd modlfyin,! AX changes 'the,.,~econd half ofEAX. (The otber rw:eW n:gi terswiUwod m. a similar fashion.) You'U need to I,dd. some "dummy" n]lf~:mbers to the 'word ,UDd b:ytA! structures, corresponding to the other half o.f lEJ\X. E.BX" -EC~ and EDK Declare the' type of me new' registers to be DWOROI (double word), wbich should bedefined as unsligned Long. Don't fo~get that 'the x86 architecmre is Iittle-endian,

I. Design a union thratl makes 'j'[ possible '~O Vil'6W ,:I 3,2-'bit value as ei61el[ at £'1 o'a t or ibe strueture describedin Exercise 14. Wrib!':a. prol,gTa:m 'that stores 1 in the stmcmre's sign field, 128 in the exponent 6eld,~ and 0 in this fra eti on, field. then prints Uu~fl Oil t value stnred in 'the union. (The answer should be -2.0 if you've set up the biit-fi,e]d'9 IC.Dnl~{::Uy ..

You might also like