[Tutor] FW: Serial Communication

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Sep 19 18:22:31 EDT 2003



Hi Shantanoo,



Looks like you're doing a lot of bit manipulation here; you'll definitely
want to look into the 'struct' module:

    http://www.python.org/doc/lib/module-struct.html

to convert between bytes and Python objects.




> 	1) a='AB'
> 	let
> 	b = a[0]^a[1]
> 	in C/C++
> 	how do i do this in python


When you say:

    b = a[0] ^ a[1]

it looks like you're trying to use the bitwise XOR operator. But since 'a'
is a string, this won't work. To use bit operations, you need to be
working with numbers.  We can convert between strings and their ascii
ordinal values by using the ord() builtin:

###
>>> s = "AB"
>>> b1 = ord(s[0])
>>> b2 = ord(s[1])
>>> b1
65
>>> b2
66
###



And once we have numbers, bitwise manipulation should work as you expect:

###
>>> b1 ^ b2
3
###


One way to more easily convert a string into a list of its ordinal numbers
a list comprehension or the map() builtin function:

###
>>> [ord(x) for x in "Hello world"]
[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
>>>
>>>
>>> map(ord, "Hello world")
[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
###




>
> 	2) a='ABC'
> 	let
> 	print("%X,%X",a[0],a[1]);
> 	output is 41,42
> 	in C/C++
> 	again how do i get this one.


You can find a way to do that in Python by using the String Formatting
operator:

    http://www.python.org/doc/lib/typesseq-strings.html


Good luck to you!




More information about the Tutor mailing list