Chapter 14: Low-Level Programming

Example 14.14, Page number: 14.12

In [1]:
a=0xf05a

print "%u" %(a)
print "%x" %(a>>6)
61530
3c1

Example 14.16, Page number: 14.13

In [4]:
a=1
nbits=16
m=0x1<<(nbits-1)

def main(a):
    mask=abs(m)
    for count in range(1,nbits+1):
        if a&mask:
            b=1
        else:
            b=0

        print "%x" %(b),
        if count%4==0:
            print "\t",

        mask>>=1
    return
print "\n1-->\n"
main(1)
print "\n-1-->\n"
main(-1)
print "\n0-->\n"
main(0)
print "\n2-->\n"
main(2)
print "\n-2-->\n"
main(-2)
1-->

0 0 0 0 	0 0 0 0 	0 0 0 0 	0 0 0 1 	
-1-->

1 1 1 1 	1 1 1 1 	1 1 1 1 	1 1 1 1 	
0-->

0 0 0 0 	0 0 0 0 	0 0 0 0 	0 0 0 0 	
2-->

0 0 0 0 	0 0 0 0 	0 0 0 0 	0 0 1 0 	
-2-->

1 1 1 1 	1 1 1 1 	1 1 1 1 	1 1 1 0 	

Example 14.23, Page Number: 14.20

In [5]:
from ctypes import *

string=c_char*50


def convert(mm,dd,yy):
    yy-=1900
    ndays=long(30.42*(mm-1)+dd)
    if mm==2:
        ndays+=1
    if mm>2 and mm<8:
        ndays-=1
    if yy%4==0 and mm<2:
        ndays+=1

    ncycles=yy/4
    ndays+=ncycles*1461

    nyears=yy%4
    if nyears>0:
        ndays+=365*nyears+1
    if ndays>59:
        ndays-=1

    day=ndays%7
    yy+=1900
    if yy%4==0 and yy%400!=0:
        day+=1
    return day


class date(Structure):
	_fields_=[('month',c_int),('day',c_int),('year',c_int)]
	

class person(Structure):
	_fields_=[('name',string),('birthdate',date)]
		
student=[]

weekday=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

month=['January','February','March','April','May','June','July','August',\
       'September','October','November','December']


name='Rob Smith'
birthdate=date(7,20,1972)
student.append(person(name,birthdate))

name='Judy Thompson'
birthdate=date(11,27,1983)
student.append(person(name,birthdate))

name='Jim Williams'
birthdate=date(12,29,1998)
student.append(person(name,birthdate))

name='Mort Davis'
birthdate=date(6,10,2010)
student.append(person(name,birthdate))


	
for count in xrange(0,4):
    day_of_week=convert(student[count].birthdate.month,student[count].birthdate.day,student[count].birthdate.year)
    print student[count].name,
    print "          %s, %s %d %d \n" %(weekday[day_of_week],month[student[count].birthdate.month-1],student[count].birthdate.day,student[count].birthdate.year)
Rob Smith           Thursday, July 20 1972 

Judy Thompson           Sunday, November 27 1983 

Jim Williams           Tuesday, December 29 1998 

Mort Davis           Thursday, June 10 2010 

In [ ]: