[BangPypers] Handling bit sized fields in network headers

Vishal vsapre80 at gmail.com
Mon May 7 08:51:36 CEST 2012


Hi,

is this some standard protocol, if yes, then use a tool like scapy. If this
is non-standard or proprietary packet...I would suggest you to read the
incoming bytes as strings and then use functions like below to extract data
from specific bit fields:

def field(num, startBit, endBit, val=None):
    """
    this function can read/manipulate a bit field
    (specified by start and end bits) in a number.
    if val is None, a read is done, else a write is performed
    requirement: startBit < endBit
    """
    mask = ~(-1 << (endBit - startBit + 1))

    # if val is None, read the field and return it.
    if(val is None):
        return (num >> startBit) & mask

    # if val is 0, write 0 in the given field
    elif(val is 0x0):
        return num & ~(mask << startBit)

    # write specific value in the given field.
    else:
        return (val << startBit) | num & ~(mask << startBit)

If you have to do this many times, you can make single line versions of
specific cases and just inline it, instead of calling a function.

Enjoy,
Vishal

On Fri, May 4, 2012 at 3:40 PM, Balachandran Sivakumar <benignbala at gmail.com
> wrote:

> Hi,
>
>          What is the best way to handle bit sized fileds in network
> headers, if the data is binary ? The struct module doesn't support
> sizes in bits, and I have scenarios where there are fields of 2 bits,
> 3 bits and 5 bits in size. Thanks
>
> --
> Thank you
> Balachandran Sivakumar
>
> Arise Awake and stop not till the goal is reached.
>                                                              - Swami
> Vivekananda
>
> Mail: benignbala at gmail.com
> Blog: http://benignbala.wordpress.com/
> _______________________________________________
> BangPypers mailing list
> BangPypers at python.org
> http://mail.python.org/mailman/listinfo/bangpypers
>



-- 
Thanks and best regards,
Vishal Sapre

---
"Life is 10% how you make it, and 90% how you take it"
"बहुजन हिताय, बहुजन सुखाय (Benefit for most people, Happiness for most
people.)"
---
Please DONT print this email, unless you really need to.
Save Energy & Paper. Save the Earth.


More information about the BangPypers mailing list