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>

<h1>EDIT</h1>

<ol>
<li>no <code>"i"</code> is not a valid encoding to use <code>str.decode</code> 

<ul>
<li>see <a href="https://docs.python.org/2/library/codecs.html#standard-encodings" rel="nofollow">https://docs.python.org/2/library/codecs.html#standard-encodings</a></li>
</ul></li>
<li>no <code>"utf-8"</code> is not a valid format string to pass to <code>struct.unpack</code> 

<ul>
<li>see <a href="https://docs.python.org/3/library/struct.html#format-characters" rel="nofollow">https://docs.python.org/3/library/struct.html#format-characters</a></li>
</ul></li>
</ol>

<h1>old anser ...</h1>

<p><code>struct.unpack</code> is not the right tool to use here</p>

<pre><code>b'11:10:00\x00ng '.decode("utf8")
b'+\r\x00\x00'.decode("utf8")
</code></pre>

<p>you simply want to decode the bytes to a unicode string I believe</p>

<p>if you want to <code>struct.unpack</code> a string you can ... but its just unpacking a bytestring</p>

<pre><code>fmt = "bb5s" #2 bytes and a string of length 5
struct.unpack(fmt,b"\x00\x12\x33\x43\x55\x77\x65")

#result: (0, 18, b'3CUwe')
</code></pre>

python struct