converting an array of chars to a string

Bjorn Pettersen BPettersen at NAREX.com
Mon Jun 24 11:59:05 EDT 2002


> From: JB [mailto:jblazi at hotmail.com] 
> 
> Bengt Richter wrote:
> 
> > Have a look at the array module. It can construct an array
> > of signed or unsigned character elements optionally 
> initialized with 
> > values from a list or string.
> [...]
> 
> Thank you very much. In principle, this was exactly, for 
> what I was looking. But most unforunately if I declare such 
> an array a, then
> 
> a[0]=210
> a[0] += 46
> 
> produces an error instead of the correct result 0. Now I am 
> a bit desperate.

Python helpfully gives you an OverflowError since that's technically
what it is. Having the value magically truncated would surprise even
more people. The simple solution is of course:

  def byteAdd(a, b):
      return (a + b) % 256

  a[0] = byteAdd(a[0], 46)

hth,
-- bjorn





More information about the Python-list mailing list