[Tutor] array('c')

Stefan Behnel stefan_ml at behnel.de
Thu May 1 17:46:08 CEST 2014


Ian D, 01.05.2014 16:38:
> I have this part of code and am unsure as to the effect of the array('c') part.

The argument that you pass into the constructor is a type identifier.

https://docs.python.org/2/library/array.html#array.array

The different types are defined at the top of that page.

It seems that you are using Python 2, BTW. In Python 3, the "c" type is not
supported anymore. I guess that's because characters do not actually exist
at the C level, only bytes (which are represented by "b" and "B").


> n = len(cmd)
>        a = array('c')
>        a.append(chr((n>> 24) & 0xFF))
>        a.append(chr((n>> 16) & 0xFF))
>        a.append(chr((n>>  8) & 0xFF))
>        a.append(chr(n & 0xFF))
>        scratchSock.send(a.tostring() + cmd) 		 	   		  

You don't have to pass in strings. Integers will do just fine.

The code above looks way too complicated, though. You might want to take a
look at the struct module instead, which allows you to do C level
formatting of simple and compound values.

Stefan




More information about the Tutor mailing list