A simple case of struct, but getting a "bad char" error
<p>I'm attempting to read a section of a binary file, and decode it as a string of characters using the struct. module. </p>

<p>It's a simple enough case. Here is the bytes argument:</p>

<pre><code>b'11:10:00\x00ng '
</code></pre>

<p>and here is the function I am attempting to use: </p>

<pre><code>struct.unpack('utf-8', b'11:10:00\x00ng ')
</code></pre>

<p>The output should be twelve characters, no?:</p>

<pre><code>'11:10:00 ng '
</code></pre>

<p>It returns <code>"struct.error bad char in struct format"</code> for some reason. What's going on? I tried a lot of resources but nobody had an example of this happening. I've tried other formats besides <code>'utf-8'</code>, such as <code>'ascii'</code>.</p>

<p>edit - there seems to be confusion; maybe i should have given my problem in less general terms: </p>

<p>I am attempting to write a command that will decode a bytes object created using f.read, in a variable format, and I tried to do it this way: </p>

<p>Value = struct.unpack(Format, Bytes)[0]</p>

<p>where
Bytes = f.read(Length)
and
Format = 'i' 
or 'd' or whatever it needs to be. </p>

<p>What I tried worked great for the case of an integer ('i') but did not work for the case of a string of characters - I got the error instead, and I'm trying to figure out why. Thanks for any help!</p>

<p>edit2 - for anyone coming after me, it looks like this is simply not possible to handle in python with a single function, because the struct.unpack function doesn't handle unicode strings and the decode. function doesn't handle encoded numbers. The only way to do what I need to do appears to be to use an if: to apply the proper function for the format</p>

<p>The struct module does a completely different job from what you're trying to do. It's for deserializing data that looks like serialized C structs (hence the name). <code>int</code>s, <code>double</code>s, fixed-size <code>char</code> arrays, things like that, packed together in a rigid layout with fixed alignment and padding. If you look at the <a href="https://docs.python.org/2/library/struct.html" rel="nofollow">docs</a>, you'll see nothing related to Unicode codecs, and the format string argument format looks nothing like a codec name.</p>

<p>You want the built-in bytestring <code>decode</code> method, which does Unicode decoding:</p>

<pre><code>b'11:10:00\x00ng '.decode('utf-8')
</code></pre>

<p>though that <code>\x00</code> will still be a Unicode NUL, not a space, because Unicode doesn't work like that.</p>

python struct