Note that there are some explanatory texts on larger screens.

plurals
  1. POImplementing C's enum and union in python
    primarykey
    data
    text
    <p>I'm trying to figure out some C code so that I can port it into python. The code is for reading a proprietary binary data file format. It has been straightforward thus far -- it's mainly been structs and I have been using the <code>struct</code> library to ask for particular ctypes from the file. However, I just came up on this bit of code and I'm at a loss for how to implement it in python. In particular, I'm not sure how to deal with the <code>enum</code> or the <code>union</code>.</p> <pre><code>#define BYTE char #define UBYTE unsigned char #define WORD short #define UWORD unsigned short typedef enum { TEEG_EVENT_TAB1=1, TEEG_EVENT_TAB2=2 } TEEG_TYPE; typedef struct { TEEG_TYPE Teeg; long Size; union { void *Ptr; // Memory pointer long Offset }; } TEEG; </code></pre> <p>Secondly, in the below struct definition, I'm not sure what the colons after the variable names mean, (e.g., <code>KeyPad:4</code>). Does it mean I'm supposed to read 4 bytes?</p> <pre><code>typedef struct { UWORD StimType; UBYTE KeyBoard; UBYTE KeyPad:4; UBYTE Accept:4; long Offset; } EVENT1; </code></pre> <p>In case it's useful, an abstract example of the way I've been accessing the file in python is as follows:</p> <pre> from struct import unpack, calcsize def get(ctype, size=1): """Reads and unpacks binary data into the desired ctype.""" if size == 1: size = '' else: size = str(size) chunk = file.read(calcsize(size + ctype)) return unpack(size + ctype, chunk)[0] file = open("file.bin", "rb") file.seek(1234) var1 = get('i') var2 = get('4l') var3 = get('10s') </pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload