473,503 Members | 2,157 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Writing bitfields with varying field lengths

In order to familiarize my self with Flash files and their bytecode I've
started to make an assembler. My first problem is writing the bitfields
the format uses often. It is a series of fields, each can be a different
number of bits, combined into the least amount of bytes possible. Extra
bits in the last byte are padded with zeros. I would like to make a
function that takes a size and value for each field needed, calculate
the amount of needed bytes, place the values, and the nretun a binary
string of the resulting bitfield. I am at a complete loss on how to
place the values into the field. I've Googled but have found nothing
helpful. Can anybody help?

Jul 18 '05 #1
2 3168
Grumfish wrote:
In order to familiarize my self with Flash files and their bytecode
I've started to make an assembler. My first problem is writing the
bitfields the format uses often. It is a series of fields, each can be
a different number of bits, combined into the least amount of bytes
possible. Extra bits in the last byte are padded with zeros. I would
like to make a function that takes a size and value for each field
needed, calculate the amount of needed bytes, place the values, and
the nretun a binary string of the resulting bitfield. I am at a
complete loss on how to place the values into the field. I've Googled
but have found nothing helpful. Can anybody help?


This should help you get started. There are more efficient ways to do
the work, but this is easily followed (hopefully):

def packBitField( * items ):
"""Pack any size set of boolean values into binary string"""
result = []
items = list(items)
while len(items)>=8:
result.append( pack8( items[:8] ) )
del items[:8]
if items:
result.append( pack8( items+([0]*(8-len(items)) ) ))
return "".join( result )

def pack8( items ):
"""Pack 8 booleans into a byte"""
value = 0
for x in range(len(items)):
value += (not not items[x])<<x
return chr(value)

if __name__ == "__main__":
print repr(packBitField( 0 ))
print repr(packBitField( 1 ))
print repr(packBitField( 0,1 ))
print repr(packBitField( 1,1 ))
print repr(packBitField( 0,0,1 ))
print repr(packBitField( 1,0,1 ))
print repr(packBitField( 0,1,1 ))
print repr(packBitField( 1,1,1 ))
print repr(packBitField( 0,0,0,0,0,0,0,0,1 ))

Enjoy,
Mike

_______________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://members.rogers.com/mcfletch/


Jul 18 '05 #2
On Mon, 18 Aug 2003 23:32:49 GMT, Grumfish <no****@nowhere.com> wrote:
In order to familiarize my self with Flash files and their bytecode I've
started to make an assembler. My first problem is writing the bitfields
the format uses often. It is a series of fields, each can be a different
number of bits, combined into the least amount of bytes possible. Extra
bits in the last byte are padded with zeros. I would like to make a
function that takes a size and value for each field needed, calculate
the amount of needed bytes, place the values, and the nretun a binary
string of the resulting bitfield. I am at a complete loss on how to
place the values into the field. I've Googled but have found nothing
helpful. Can anybody help?

Well, a Python integer or long can hold a large number of bits, so your
problem is just how to specify a narrow field. The simplest thing is probably
just to use tuples to specify bits in an integer, and how many you mean
in the other element of the tuple, e.g., (bit_integer, number_of_bits),
or (bi,nb) for short. You could then give some opcode and flagbit constants
names, e.g.,

FROOBLE = (0x13, 5)
FROZ_ON = (0X1, 1)
FROZ_OFF = (0x0, 1)
FRAZZLE = (0xff1, 12)

Then if you wanted to pack those into a single bit sequence with FROOBLE at
the most significant end and FRAZZLE at the least, thus:

+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|1 0 0 1 1|1|1 1 1 1 1 1 1 1 0 0 0 1|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
\frooble/ ^ \______frazzle________/
|
+-froz_on

you could write a packer, that takes the list and returns a single combined tuple, e.g.,
....(later...) actually, why not a Bitfield class that will show interactively and
that you can just add to join bitfields? E.g., (hot out of the kitchen, not very tested)

====< bitfield.py >================================================= ======
class Bitfield(tuple):
"""Instantiate by Bitfield() for Bitfield(0,0), or Bitfield(bitdata, nbits)"""
def __new__(cls, *args):
if not args: args = (0,0) #default zero width bitfield
return tuple.__new__(cls, args)
def __repr__(self):
bits, nb = self
return '<BF[%d]:%r>'%(nb,''.join([chr(48+((bits>>(nb-1-i))&1)) for i in xrange(nb)]))
def __add__(self, *others):
"""Add another bitfield or sequence of bitfield objects"""
if others and not isinstance(others[0], Bitfield): others = others[0]
combo, totb = self
for bf, nb in others:
combo = (combo<<nb)|(bf&((1L<<nb)-1)) # or just (bits<<nb)|bf if bf value trusted
totb += nb
return Bitfield(combo, totb)
def rpadto(self, align):
frag = self[1]%align
if frag==0: return self
return self + Bitfield(0,align-frag)
def lpadto(self,align):
frag = self[1]%align
if frag==0: return self
return Bitfield(0,align-frag)+self

FROOBLE = Bitfield(0x13, 5)
FROZ_ON = Bitfield(0x1, 1)
FROZ_OFF = Bitfield(0x0, 1)
FRAZZLE = Bitfield(0xff1, 12)

def test():
# example use:
bf_seq = [FROOBLE, FROZ_ON, FRAZZLE]
print 'bf_seq:', bf_seq

combined_bitfield = Bitfield() + bf_seq
print 'combined_bitfield:', combined_bitfield

bf, nbits = combined_bitfield
# pad to an even byte on the right, if desired, e.g.,
right_padded = combined_bitfield.rpadto(8)
left_padded = combined_bitfield.lpadto(8)
print 'right_padded:', right_padded
print ' left_padded:', left_padded

if __name__ == '__main__':
test()
================================================== ========================
Oop, forgot to docstring rpadto and lpadto, but they obviously pad on
respective sides to make the full width a multiple of the specified alignment
width.

The test gives this result:

bf_seq: [<BF[5]:'10011'>, <BF[1]:'1'>, <BF[12]:'111111110001'>]
combined_bitfield: <BF[18]:'100111111111110001'>
right_padded: <BF[24]:'100111111111110001000000'>
left_padded: <BF[24]:'000000100111111111110001'>

If we spread the combined bits out so we can compare, we get

<BF[18]:
'1 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1'>
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|1 0 0 1 1|1|1 1 1 1 1 1 1 1 0 0 0 1|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
\frooble/ ^ \______frazzle________/
|
+-froz_on
You can play with this interactively, e.g.,
import bitfield
BF = bitfield.Bitfield # for short
BF() # zero width field <BF[0]:''> BF() + BF(0xa,4) <BF[4]:'1010'> BF() + BF(0xa,4)+ BF(07,3) <BF[7]:'1010111'> BF() + BF(0xa,4)+ BF(07,3)+BF(0,1) <BF[8]:'10101110'> byte = BF() + BF(0xa,4)+ BF(07,3)+BF(0,1)
byte <BF[8]:'10101110'> bits, nb = byte
hex(bits) '0xAEL' nb 8 byte <BF[8]:'10101110'> BF(-1, 5) <BF[5]:'11111'> BF(-1, 0)

<BF[0]:''>

HTH

Regards,
Bengt Richter
Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
1892
by: Régis Troadec | last post by:
Hi all, I follow c.l.c. for only a short time and I would like to know why there isn't anything concerning bitfields among the FAQs. Is it because ... 1. of portability issues? 2. bitfields...
6
2666
by: GalenTX | last post by:
I am looking for opinions on a possible approach to coping with bitfields in a heterogenous environment. We've got a bunch of legacy code which maps to hardware using bitfields. The code was...
19
14790
by: Mehta Shailendrakumar | last post by:
Hi, I would like to know why array of bitfields is not possible. Is there any relation with processor architecture for this? Thank you for your time. Regards, Shailendra
2
8107
by: Jason Curl | last post by:
Hello C Group, From what I remember, it is implementation dependent the way that a compiler may order bitfields in a struct. In the example program I give, Solaris Sparc gives one result, Intel...
31
3004
by: Zero | last post by:
Hi everybody! Is it possible to write a value into a bit field which initializes all bits? example: struct Field { unsigned int Bit1 : 1;
18
4682
by: richard_l | last post by:
Hello All, I am writing an application which receives a word which is a bitmap. I have created a word typedef which contains a bitfield defining each bit. however, I was wondering however if it...
7
1945
by: sarathy | last post by:
Hi, 1. How it that the results for the size of struct1 and struct2 (below) are 4 and 3 # include <stdio.h> struct struct1 { const :16;
9
19242
by: cman | last post by:
Who can explain to me what bitfields are and how to use them in practice? I would need a fairly detailed explaination, I would be a newbie to advanced C programming features. What are the...
7
2461
by: servantofone | last post by:
I'm using Access 2003. I'm building a query and wish to display all records with values in a certain field (HIST) made up of all zeros. The field has a range of text values including alpha-numeric...
0
7205
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7093
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7349
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7008
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5594
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5022
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3177
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3168
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
399
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.