Can't create small bitfields
Rob Gaddi <[email protected]> Tue, 15 Apr 2014 17:01:26 -0700
| Newsgroups | gmane.comp.python.ctypes |
|---|---|
| Message-ID | <[email protected]> |
I'm trying to build up bitfields that are smaller than the word size of
the machine, only 1 or 2 bytes. Unfortunately, the smallest Structure
I can get is 4 bytes. Any ideas on what I'm doing wrong? OS is
x86_64 Ubuntu, Python is 2.7.4 or 3.3.1 with equal results. Sample code
below.
---
from __future__ import print_function
from ctypes import *
class Struct(Structure):
_pack_ = 1
Struct._fields_ = [
('low', c_uint, 4),
('high', c_uint, 4),
]
x = Struct(low = 1, high = 2)
print('Structure Size:', sizeof(Struct))
print('Instance Size:', sizeof(x))
print('Structure Fields:', Struct.low, Struct.high)
print('Instance Fields:', x.low, x.high)
arr = (c_uint8 * sizeof(x)).from_buffer(x)
print('Bytes:', ','.join('{0:02X}'.format(b) for b in arr))
---
$python_vme_mods$ python test_bitfield.py
Structure Size: 4
Instance Size: 4
Structure Fields: <Field type=c_uint, ofs=0:0, bits=4> <Field
type=c_uint, ofs=0:4, bits=4> Instance Fields: 1 2
Bytes: 21,00,00,00
--
Rob Gaddi, Highland Technology
18 Otis St.
San Francisco, CA 94103
415-551-1700
------------------------------------------------------------------------------
Learn Graph Databases - Download FREE O'Reilly Book
"Graph Databases" is the definitive new guide to graph databases and their
applications. Written by three acclaimed leaders in the field,
this first edition is now available. Download your free book today!
http://p.sf.net/sfu/NeoTech