[IronPython] How to convert a 'str' type to byteArray
vernondcole at gmail.com
Wed Nov 11 20:47:23 CET 2009
Make sure what data type is really being returned by part.getpayload() .
Perhaps it is already in a suitable for when you get it?
The Python 2.x language method of loading a binary blob of memory is to use
the built in function "buffer"
s = 'this is a string'
b = buffer(s)
"b" will be accepted my a byte arrary in most cases.
but make sure that what you have is a legal ASCII string. CPython stores
"strings" in ASCII and "unicode" differently. Iron Python stores "strings"
in unicode, and buffer() tries to be smart about hiding that fact, in order
to act like CPython in the easy cases. The above will work the same in
either IronPython or CPython.
On the other hand, in CPython:
u = u'this is a unicode string'
b = buffer(u)
will produce a blob twice (or four times) as long as the above, since it
stores all 16 (or 32) bits of the character code.
(IronPython seems to store them internally in UTF-8 or some similar code.)
To convert to "proper" 8-bit codes you must use something like:
u = u'unicode string'
b = buffer(u.encode('latin-1'))
Python 3.x removes the problem by defining all character strings as unicode
(as IronPython does now), and providing a byte() function, in which each 8
byte is treated as an integer, rather than a character. That will make
things simpler in the future.
On Wed, Nov 11, 2009 at 8:14 AM, matan keret <matan504 at gmail.com> wrote:
> I have the following code which gets an image from an email.
> after getting it i need to pass it as a byteArray (byte in C#) to a C#
> i tried all sorts of things but no luck. I'm using ironPython 2.0.3
> the important parts of the code are:
> # getting the image from the e-mail
> image = part.get_payload()
> # my try to cast the str into a byteArray
> byteArray = BitConverter.GetBytes(image.ToCharArray())
> this last line returns 1 byte and doesn't seem to do the job.
> is there any equivalent to the 'bytearray(image)' function in CPython?
> Users mailing list
> Users at lists.ironpython.com
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Ironpython-users