[Haskell] Finding the length of a String in bytes

Piotr Kalinowski pitkali at gmail.com
Thu Jun 22 16:51:36 EDT 2006


On 22/06/06, David House <dmhouse at gmail.com> wrote:
> I recently needed to add a Content-Length header to my HTTP request
> forged with Network.HTTP [1]. However, this needs to be the length of
> the body content in bytes, not characters. Without assuming the
> characters will all be ASCII, is there an easy way of doing this?
> length seems to have the correct results, but I'm uneasy about relying
> on this.

Is your string a string of unicode characters, or just a string read
from somewhere in some encoding (in which case the value of each
character is less than 256). In former case length function will fail
to give correct result if you use multi-byte encoding like utf-8.
You'd need to do the conversion and only then count length of the
resulting sequence.

In latter case length is always good, because you really have string
of bytes that encode your content in some encoding, not characters, in
a way.

Regards,
Piotr Kalinowski

-- 
Intelligence is like a river: the deeper it is, the less noise it makes


More information about the Haskell mailing list