bitstruct-3.7.0/0000775000175000017500000000000013224121366013454 5ustar erikerik00000000000000bitstruct-3.7.0/README.rst0000664000175000017500000000737013173075037015160 0ustar erikerik00000000000000|buildstatus|_ |coverage|_ About ===== This module is intended to have a similar interface as the python struct module, but working on bits instead of primitive data types (char, int, ...). Project homepage: https://github.com/eerimoq/bitstruct Documentation: http://bitstruct.readthedocs.org/en/latest Installation ============ .. code-block:: python pip install bitstruct Example usage ============= A basic example of `packing`_ and `unpacking`_ four integers using the format string ``'u1u3u4s16'``: .. code-block:: python >>> from bitstruct import * >>> pack('u1u3u4s16', 1, 2, 3, -4) b'\xa3\xff\xfc' >>> unpack('u1u3u4s16', b'\xa3\xff\xfc') (1, 2, 3, -4) >>> calcsize('u1u3u4s16') 24 An example `compiling`_ the format string once, and use it to `pack`_ and `unpack`_ data: .. code-block:: python >>> import bitstruct >>> cf = bitstruct.compile('u1u3u4s16') >>> cf.pack(1, 2, 3, -4) b'\xa3\xff\xfc' >>> cf.unpack(b'\xa3\xff\xfc') (1, 2, 3, -4) The unpacked values can be named by assigning them to variables or by wrapping the result in a named tuple: .. code-block:: python >>> from bitstruct import * >>> from collections import namedtuple >>> MyName = namedtuple('myname', [ 'a', 'b', 'c', 'd' ]) >>> unpacked = unpack('u1u3u4s16', b'\xa3\xff\xfc') >>> myname = MyName(*unpacked) >>> myname myname(a=1, b=2, c=3, d=-4) >>> myname.c 3 An example of `packing`_ and `unpacking`_ an unsinged integer, a signed integer, a float, a boolean, a byte string and a string: .. code-block:: python >>> from bitstruct import * >>> pack('u5s5f32b1r13t40', 1, -1, 3.75, True, b'\xff\xff', 'hello') b'\x0f\xd0\x1c\x00\x00?\xffhello' >>> unpack('u5s5f32b1r13t40', b'\x0f\xd0\x1c\x00\x00?\xffhello') (1, -1, 3.75, True, b'\xff\xf8', 'hello') >>> calcsize('u5s5f32b1r13t40') 96 The same format string and values as in the previous example, but using LSB (Least Significant Bit) first instead of the default MSB (Most Significant Bit) first: .. code-block:: python >>> from bitstruct import * >>> pack('>> unpack('>> calcsize('>> from bitstruct import * >>> from binascii import unhexlify >>> unpack('s17s13r24', unhexlify('0123456789abcdef')) (582, -3751, b'\xe2j\xf3') >>> with open("test.bin", "rb") as fin: ... unpack('s17s13r24', fin.read(8)) ... ... (582, -3751, b'\xe2j\xf3') Change endianness of the data with `byteswap`_, and then unpack the values: .. code-block:: python >>> from bitstruct import * >>> packed = pack('u1u3u4s16', 1, 2, 3, 1) >>> unpack('u1u3u4s16', byteswap('12', packed)) (1, 2, 3, 256) .. |buildstatus| image:: https://travis-ci.org/eerimoq/bitstruct.svg .. _buildstatus: https://travis-ci.org/eerimoq/bitstruct .. |coverage| image:: https://coveralls.io/repos/github/eerimoq/bitstruct/badge.svg?branch=master .. _coverage: https://coveralls.io/github/eerimoq/bitstruct .. _packing: http://bitstruct.readthedocs.io/en/latest/#bitstruct.pack .. _unpacking: http://bitstruct.readthedocs.io/en/latest/#bitstruct.unpack .. _pack: http://bitstruct.readthedocs.io/en/latest/#bitstruct.CompiledFormat.pack .. _unpack: http://bitstruct.readthedocs.io/en/latest/#bitstruct.CompiledFormat.unpack .. _byteswap: http://bitstruct.readthedocs.io/en/latest/#bitstruct.byteswap .. _compiling: http://bitstruct.readthedocs.io/en/latest/#bitstruct.compile bitstruct-3.7.0/LICENSE0000664000175000017500000000207513224121211014452 0ustar erikerik00000000000000The MIT License (MIT) Copyright (c) 2015-2018 Erik Moqvist Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. bitstruct-3.7.0/setup.cfg0000664000175000017500000000004613224121366015275 0ustar erikerik00000000000000[egg_info] tag_build = tag_date = 0 bitstruct-3.7.0/PKG-INFO0000664000175000017500000001250613224121366014555 0ustar erikerik00000000000000Metadata-Version: 1.1 Name: bitstruct Version: 3.7.0 Summary: This module performs conversions between Python values and C bit field structs represented as Python byte strings. Home-page: https://github.com/eerimoq/bitstruct Author: Erik Moqvist, Ilya Petukhov Author-email: erik.moqvist@gmail.com License: MIT Description: |buildstatus|_ |coverage|_ About ===== This module is intended to have a similar interface as the python struct module, but working on bits instead of primitive data types (char, int, ...). Project homepage: https://github.com/eerimoq/bitstruct Documentation: http://bitstruct.readthedocs.org/en/latest Installation ============ .. code-block:: python pip install bitstruct Example usage ============= A basic example of `packing`_ and `unpacking`_ four integers using the format string ``'u1u3u4s16'``: .. code-block:: python >>> from bitstruct import * >>> pack('u1u3u4s16', 1, 2, 3, -4) b'\xa3\xff\xfc' >>> unpack('u1u3u4s16', b'\xa3\xff\xfc') (1, 2, 3, -4) >>> calcsize('u1u3u4s16') 24 An example `compiling`_ the format string once, and use it to `pack`_ and `unpack`_ data: .. code-block:: python >>> import bitstruct >>> cf = bitstruct.compile('u1u3u4s16') >>> cf.pack(1, 2, 3, -4) b'\xa3\xff\xfc' >>> cf.unpack(b'\xa3\xff\xfc') (1, 2, 3, -4) The unpacked values can be named by assigning them to variables or by wrapping the result in a named tuple: .. code-block:: python >>> from bitstruct import * >>> from collections import namedtuple >>> MyName = namedtuple('myname', [ 'a', 'b', 'c', 'd' ]) >>> unpacked = unpack('u1u3u4s16', b'\xa3\xff\xfc') >>> myname = MyName(*unpacked) >>> myname myname(a=1, b=2, c=3, d=-4) >>> myname.c 3 An example of `packing`_ and `unpacking`_ an unsinged integer, a signed integer, a float, a boolean, a byte string and a string: .. code-block:: python >>> from bitstruct import * >>> pack('u5s5f32b1r13t40', 1, -1, 3.75, True, b'\xff\xff', 'hello') b'\x0f\xd0\x1c\x00\x00?\xffhello' >>> unpack('u5s5f32b1r13t40', b'\x0f\xd0\x1c\x00\x00?\xffhello') (1, -1, 3.75, True, b'\xff\xf8', 'hello') >>> calcsize('u5s5f32b1r13t40') 96 The same format string and values as in the previous example, but using LSB (Least Significant Bit) first instead of the default MSB (Most Significant Bit) first: .. code-block:: python >>> from bitstruct import * >>> pack('>> unpack('>> calcsize('>> from bitstruct import * >>> from binascii import unhexlify >>> unpack('s17s13r24', unhexlify('0123456789abcdef')) (582, -3751, b'\xe2j\xf3') >>> with open("test.bin", "rb") as fin: ... unpack('s17s13r24', fin.read(8)) ... ... (582, -3751, b'\xe2j\xf3') Change endianness of the data with `byteswap`_, and then unpack the values: .. code-block:: python >>> from bitstruct import * >>> packed = pack('u1u3u4s16', 1, 2, 3, 1) >>> unpack('u1u3u4s16', byteswap('12', packed)) (1, 2, 3, 256) .. |buildstatus| image:: https://travis-ci.org/eerimoq/bitstruct.svg .. _buildstatus: https://travis-ci.org/eerimoq/bitstruct .. |coverage| image:: https://coveralls.io/repos/github/eerimoq/bitstruct/badge.svg?branch=master .. _coverage: https://coveralls.io/github/eerimoq/bitstruct .. _packing: http://bitstruct.readthedocs.io/en/latest/#bitstruct.pack .. _unpacking: http://bitstruct.readthedocs.io/en/latest/#bitstruct.unpack .. _pack: http://bitstruct.readthedocs.io/en/latest/#bitstruct.CompiledFormat.pack .. _unpack: http://bitstruct.readthedocs.io/en/latest/#bitstruct.CompiledFormat.unpack .. _byteswap: http://bitstruct.readthedocs.io/en/latest/#bitstruct.byteswap .. _compiling: http://bitstruct.readthedocs.io/en/latest/#bitstruct.compile Keywords: bit field,bit parsing,bit unpack,bit pack Platform: UNKNOWN Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 bitstruct-3.7.0/docs/0000775000175000017500000000000013224121366014404 5ustar erikerik00000000000000bitstruct-3.7.0/docs/make.bat0000664000175000017500000001612212760401517016016 0ustar erikerik00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled echo. coverage to run coverage check of the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) REM Check if sphinx-build is available and fallback to Python version if any %SPHINXBUILD% 2> nul if errorlevel 9009 goto sphinx_python goto sphinx_ok :sphinx_python set SPHINXBUILD=python -m sphinx.__init__ %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) :sphinx_ok if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\bitstruct.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\bitstruct.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "coverage" ( %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage if errorlevel 1 exit /b 1 echo. echo.Testing of coverage in the sources finished, look at the ^ results in %BUILDDIR%/coverage/python.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end bitstruct-3.7.0/docs/index.rst0000664000175000017500000000121613170336625016253 0ustar erikerik00000000000000.. bitstruct documentation master file, created by sphinx-quickstart on Sat Apr 25 11:54:09 2015. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. .. toctree:: :maxdepth: 2 bitstruct - Interpret strings as packed binary data =================================================== .. include:: ../README.rst Functions ========= .. autofunction:: bitstruct.pack .. autofunction:: bitstruct.unpack .. autofunction:: bitstruct.calcsize .. autofunction:: bitstruct.byteswap .. autofunction:: bitstruct.compile Classes ======= .. autoclass:: bitstruct.CompiledFormat :members: bitstruct-3.7.0/docs/conf.py0000664000175000017500000002212113224121211015666 0ustar erikerik00000000000000# -*- coding: utf-8 -*- # # bitstruct documentation build configuration file, created by # sphinx-quickstart on Sat Apr 25 11:54:09 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) import bitstruct # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'bitstruct' copyright = u'2015-2018, Erik Moqvist' author = u'Erik Moqvist' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = bitstruct.__version__ # The full version, including alpha/beta/rc tags. release = bitstruct.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'bitstructdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'bitstruct.tex', u'bitstruct Documentation', u'Erik Moqvist', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'bitstruct', u'bitstruct Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'bitstruct', u'bitstruct Documentation', author, 'bitstruct', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False bitstruct-3.7.0/docs/Makefile0000664000175000017500000001637512760401517016063 0ustar erikerik00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/bitstruct.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/bitstruct.qhc" applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/bitstruct" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/bitstruct" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." bitstruct-3.7.0/bitstruct.egg-info/0000775000175000017500000000000013224121366017171 5ustar erikerik00000000000000bitstruct-3.7.0/bitstruct.egg-info/top_level.txt0000664000175000017500000000001213224121366021714 0ustar erikerik00000000000000bitstruct bitstruct-3.7.0/bitstruct.egg-info/PKG-INFO0000664000175000017500000001250613224121366020272 0ustar erikerik00000000000000Metadata-Version: 1.1 Name: bitstruct Version: 3.7.0 Summary: This module performs conversions between Python values and C bit field structs represented as Python byte strings. Home-page: https://github.com/eerimoq/bitstruct Author: Erik Moqvist, Ilya Petukhov Author-email: erik.moqvist@gmail.com License: MIT Description: |buildstatus|_ |coverage|_ About ===== This module is intended to have a similar interface as the python struct module, but working on bits instead of primitive data types (char, int, ...). Project homepage: https://github.com/eerimoq/bitstruct Documentation: http://bitstruct.readthedocs.org/en/latest Installation ============ .. code-block:: python pip install bitstruct Example usage ============= A basic example of `packing`_ and `unpacking`_ four integers using the format string ``'u1u3u4s16'``: .. code-block:: python >>> from bitstruct import * >>> pack('u1u3u4s16', 1, 2, 3, -4) b'\xa3\xff\xfc' >>> unpack('u1u3u4s16', b'\xa3\xff\xfc') (1, 2, 3, -4) >>> calcsize('u1u3u4s16') 24 An example `compiling`_ the format string once, and use it to `pack`_ and `unpack`_ data: .. code-block:: python >>> import bitstruct >>> cf = bitstruct.compile('u1u3u4s16') >>> cf.pack(1, 2, 3, -4) b'\xa3\xff\xfc' >>> cf.unpack(b'\xa3\xff\xfc') (1, 2, 3, -4) The unpacked values can be named by assigning them to variables or by wrapping the result in a named tuple: .. code-block:: python >>> from bitstruct import * >>> from collections import namedtuple >>> MyName = namedtuple('myname', [ 'a', 'b', 'c', 'd' ]) >>> unpacked = unpack('u1u3u4s16', b'\xa3\xff\xfc') >>> myname = MyName(*unpacked) >>> myname myname(a=1, b=2, c=3, d=-4) >>> myname.c 3 An example of `packing`_ and `unpacking`_ an unsinged integer, a signed integer, a float, a boolean, a byte string and a string: .. code-block:: python >>> from bitstruct import * >>> pack('u5s5f32b1r13t40', 1, -1, 3.75, True, b'\xff\xff', 'hello') b'\x0f\xd0\x1c\x00\x00?\xffhello' >>> unpack('u5s5f32b1r13t40', b'\x0f\xd0\x1c\x00\x00?\xffhello') (1, -1, 3.75, True, b'\xff\xf8', 'hello') >>> calcsize('u5s5f32b1r13t40') 96 The same format string and values as in the previous example, but using LSB (Least Significant Bit) first instead of the default MSB (Most Significant Bit) first: .. code-block:: python >>> from bitstruct import * >>> pack('>> unpack('>> calcsize('>> from bitstruct import * >>> from binascii import unhexlify >>> unpack('s17s13r24', unhexlify('0123456789abcdef')) (582, -3751, b'\xe2j\xf3') >>> with open("test.bin", "rb") as fin: ... unpack('s17s13r24', fin.read(8)) ... ... (582, -3751, b'\xe2j\xf3') Change endianness of the data with `byteswap`_, and then unpack the values: .. code-block:: python >>> from bitstruct import * >>> packed = pack('u1u3u4s16', 1, 2, 3, 1) >>> unpack('u1u3u4s16', byteswap('12', packed)) (1, 2, 3, 256) .. |buildstatus| image:: https://travis-ci.org/eerimoq/bitstruct.svg .. _buildstatus: https://travis-ci.org/eerimoq/bitstruct .. |coverage| image:: https://coveralls.io/repos/github/eerimoq/bitstruct/badge.svg?branch=master .. _coverage: https://coveralls.io/github/eerimoq/bitstruct .. _packing: http://bitstruct.readthedocs.io/en/latest/#bitstruct.pack .. _unpacking: http://bitstruct.readthedocs.io/en/latest/#bitstruct.unpack .. _pack: http://bitstruct.readthedocs.io/en/latest/#bitstruct.CompiledFormat.pack .. _unpack: http://bitstruct.readthedocs.io/en/latest/#bitstruct.CompiledFormat.unpack .. _byteswap: http://bitstruct.readthedocs.io/en/latest/#bitstruct.byteswap .. _compiling: http://bitstruct.readthedocs.io/en/latest/#bitstruct.compile Keywords: bit field,bit parsing,bit unpack,bit pack Platform: UNKNOWN Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 bitstruct-3.7.0/bitstruct.egg-info/SOURCES.txt0000664000175000017500000000044313224121366021056 0ustar erikerik00000000000000LICENSE MANIFEST.in Makefile README.rst bitstruct.py setup.py bitstruct.egg-info/PKG-INFO bitstruct.egg-info/SOURCES.txt bitstruct.egg-info/dependency_links.txt bitstruct.egg-info/top_level.txt docs/Makefile docs/conf.py docs/index.rst docs/make.bat tests/__init__.py tests/test_bitstruct.pybitstruct-3.7.0/bitstruct.egg-info/dependency_links.txt0000664000175000017500000000000113224121366023237 0ustar erikerik00000000000000 bitstruct-3.7.0/setup.py0000775000175000017500000000150412760401517015174 0ustar erikerik00000000000000#!/usr/bin/env python from setuptools import setup import bitstruct setup(name='bitstruct', version=bitstruct.__version__, description=('This module performs conversions between Python values ' 'and C bit field structs represented as Python ' 'byte strings.'), long_description=open('README.rst', 'r').read(), author='Erik Moqvist, Ilya Petukhov', author_email='erik.moqvist@gmail.com', license='MIT', classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], keywords=['bit field', 'bit parsing', 'bit unpack', 'bit pack'], url='https://github.com/eerimoq/bitstruct', py_modules=['bitstruct'], test_suite="tests") bitstruct-3.7.0/bitstruct.py0000664000175000017500000002761213224121337016057 0ustar erikerik00000000000000from __future__ import print_function import re import struct import binascii __version__ = "3.7.0" def _parse_format(fmt): if fmt and fmt[-1] in '><': byte_order = fmt[-1] fmt = fmt[:-1] else: byte_order = '' parsed_infos = re.findall(r'([<>]?)([a-zA-Z])(\d+)', fmt) if ''.join([''.join(info) for info in parsed_infos]) != fmt: raise ValueError("bad format '{}'".format(fmt + byte_order)) # Use big endian as default and use the endianness of the previous # value if none is given for the current value. infos = [] endianness = ">" for info in parsed_infos: if info[0] != "": endianness = info[0] if info[1] not in 'supfbtr': raise ValueError("bad char '{}' in format".format(info[1])) infos.append((info[1], int(info[2]), endianness)) return infos, byte_order or '>' def _pack_integer(size, arg): value = int(arg) if value < 0: value += (1 << size) value += (1 << size) return bin(value)[3:] def _pack_boolean(size, arg): value = bool(arg) return _pack_integer(size, int(value)) def _pack_float(size, arg): value = float(arg) if size == 16: value = struct.pack('>e', value) elif size == 32: value = struct.pack('>f', value) elif size == 64: value = struct.pack('>d', value) else: raise ValueError('expected float size of 16, 32, or 64 bits (got {})'.format( size)) return bin(int(b'01' + binascii.hexlify(value), 16))[3:] def _pack_bytearray(size, arg): return bin(int(b'01' + binascii.hexlify(arg), 16))[3:size + 3] def _pack_text(size, arg): value = arg.encode('utf-8') return _pack_bytearray(size, bytearray(value)) def _unpack_signed_integer(bits): value = int(bits, 2) if bits[0] == '1': value -= (1 << len(bits)) return value def _unpack_unsigned_integer(bits): return int(bits, 2) def _unpack_boolean(bits): return bool(int(bits, 2)) def _unpack_float(size, bits): packed = _unpack_bytearray(size, bits) if size == 16: value = struct.unpack('>e', packed)[0] elif size == 32: value = struct.unpack('>f', packed)[0] elif size == 64: value = struct.unpack('>d', packed)[0] else: raise ValueError('expected float size of 16, 32, or 64 bits (got {})'.format( size)) return value def _unpack_bytearray(size, bits): rest = size % 8 if rest > 0: bits += (8 - rest) * '0' return binascii.unhexlify(hex(int('10000000' + bits, 2))[4:].strip('L')) def _unpack_text(size, bits): return _unpack_bytearray(size, bits).decode('utf-8') class CompiledFormat(object): """A compiled format string that can be used to pack and/or unpack data multiple times. Instances of this class are created by the factory function :func:`~bitstruct.compile()`. :param fmt: Bitstruct format string. See :func:`~bitstruct.pack()` for details. """ def __init__(self, fmt): infos, byte_order = _parse_format(fmt) self._infos = infos self._byte_order = byte_order self._number_of_bits_to_unpack = sum([info[1] for info in infos]) self._number_of_arguments = 0 for info in infos: if info[0] != 'p': self._number_of_arguments += 1 def pack(self, *args): """Return a byte string containing the values v1, v2, ... packed according to the compiled format string. If the total number of bits are not a multiple of 8, padding will be added at the end of the last byte. :param args: Variable argument list of values to pack. :returns: A byte string of the packed values. """ bits = '' i = 0 # Sanity check of the number of arguments. if len(args) < self._number_of_arguments: raise ValueError("pack expected {} item(s) for packing " "(got {})".format(self._number_of_arguments, len(args))) for type_, size, endianness in self._infos: if type_ == 'p': bits += size * '0' else: if type_ == 's': value_bits = _pack_integer(size, args[i]) elif type_ == 'u': value_bits = _pack_integer(size, args[i]) elif type_ == 'f': value_bits = _pack_float(size, args[i]) elif type_ == 'b': value_bits = _pack_boolean(size, args[i]) elif type_ == 't': value_bits = _pack_text(size, args[i]) elif type_ == 'r': value_bits = _pack_bytearray(size, bytearray(args[i])) else: raise ValueError("bad type '{}' in format".format(type_)) # reverse the bit order in little endian values if endianness == "<": value_bits = value_bits[::-1] # reverse bytes order for least significant byte first if self._byte_order == ">": bits += value_bits else: aligned_offset = len(value_bits) - (8 - (len(bits) % 8)) while aligned_offset > 0: bits += value_bits[aligned_offset:] value_bits = value_bits[:aligned_offset] aligned_offset -= 8 bits += value_bits i += 1 # padding of last byte tail = len(bits) % 8 if tail != 0: bits += (8 - tail) * '0' return bytes(_unpack_bytearray(len(bits), bits)) def unpack(self, data): """Unpack `data` (byte string, bytearray or list of integers) according to the compiled format string. The result is a tuple even if it contains exactly one item. :param data: Byte string of values to unpack. :returns: A tuple of the unpacked values. """ bits = bin(int(b'01' + binascii.hexlify(bytearray(data)), 16))[3:] # Sanity check. if self._number_of_bits_to_unpack > len(bits): raise ValueError("unpack requires at least {} bits to unpack " "(got {})".format(self._number_of_bits_to_unpack, len(bits))) res = [] offset = 0 for type_, size, endianness in self._infos: if type_ == 'p': pass else: # reverse bytes order for least significant byte first if self._byte_order == ">": value_bits = bits[offset:offset + size] else: value_bits_tmp = bits[offset:offset + size] aligned_offset = (size - ((offset + size) % 8)) value_bits = '' while aligned_offset > 0: value_bits += value_bits_tmp[aligned_offset:aligned_offset + 8] value_bits_tmp = value_bits_tmp[:aligned_offset] aligned_offset -= 8 value_bits += value_bits_tmp # reverse the bit order in little endian values if endianness == "<": value_bits = value_bits[::-1] if type_ == 's': value = _unpack_signed_integer(value_bits) elif type_ == 'u': value = _unpack_unsigned_integer(value_bits) elif type_ == 'f': value = _unpack_float(size, value_bits) elif type_ == 'b': value = _unpack_boolean(value_bits) elif type_ == 't': value = _unpack_text(size, value_bits) elif type_ == 'r': value = bytes(_unpack_bytearray(size, value_bits)) else: raise ValueError("bad type '{}' in format".format(type_)) res.append(value) offset += size return tuple(res) def calcsize(self): """Calculate the number of bits in the compiled format string. :returns: Number of bits in the format string. """ return sum([size for _, size, _ in self._infos]) def pack(fmt, *args): """Return a byte string containing the values v1, v2, ... packed according to given format string `fmt`. If the total number of bits are not a multiple of 8, padding will be added at the end of the last byte. :param fmt: Bitstruct format string. See format description below. :param args: Variable argument list of values to pack. :returns: A byte string of the packed values. `fmt` is a string of bitorder-type-length groups, and optionally a byteorder identifier after the groups. Bitorder and byteorder may be omitted. Bitorder is either ``>`` or ``<``, where ``>`` means MSB first and ``<`` means LSB first. If bitorder is omitted, the previous values' bitorder is used for the current value. For example, in the format string ``'u1`` or ``<``, where ``>`` means most significant byte first and ``<`` means least significant byte first. If byteorder is omitted, most significant byte first is used. There are seven types; ``u``, ``s``, ``f``, ``b``, ``t``, ``r`` and ``p``. - ``u`` -- unsigned integer - ``s`` -- signed integer - ``f`` -- floating point number of 16, 32, or 64 bits - ``b`` -- boolean - ``t`` -- text (ascii or utf-8) - ``r`` -- raw, bytes - ``p`` -- padding, ignore Length is the number of bits to pack the value into. Example format string with default bit and byte ordering: ``'u1u3p7s16'`` Same format string, but with least significant byte first: ``'u1u3p7s16<'`` Same format string, but with LSB first (``<`` prefix) and least significant byte first (``<`` suffix): ``'= (3, 6): packed = pack('f16', 1.0) unpacked = unpack('f16', packed) self.assertEqual(unpacked, (1.0, )) def test_calcsize(self): """Calculate size. """ size = calcsize('u1u1s6u7u9') self.assertEqual(size, 24) size = calcsize('u1') self.assertEqual(size, 1) size = calcsize('u77') self.assertEqual(size, 77) size = calcsize('u1s6u7u9') self.assertEqual(size, 23) size = calcsize('b1s6u7u9p1t8') self.assertEqual(size, 32) def test_byteswap(self): """Byte swap. """ res = b'\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a' ref = b'\x01\x03\x02\x04\x08\x07\x06\x05\x0a\x09' self.assertEqual(byteswap('12142', ref), res) packed = pack('u1u5u2u16', 1, 2, 3, 4) unpacked = unpack('u1u5u2u16', byteswap('12', packed)) self.assertEqual(unpacked, (1, 2, 3, 1024)) def test_endianness(self): """Test pack/unpack with endianness information in the format string. """ # big endian ref = b'\x02\x46\x9a\xfe\x00\x00\x00' packed = pack('>u19s3f32', 0x1234, -2, -1.0) self.assertEqual(packed, ref) unpacked = unpack('>u19s3f32', packed) self.assertEqual(unpacked, (0x1234, -2, -1.0)) # little endian ref = b'\x2c\x48\x0c\x00\x00\x07\xf4' packed = pack('u19f64r3p4', 1, -2, 1.0, b'\x80') self.assertEqual(packed, ref) unpacked = unpack('>u19f64r3p4', packed) self.assertEqual(unpacked, (1, -2, 1.0, b'\x80')) # opposite endianness of the 'mixed endianness' test ref = b'\x80\x00\x1e\x00\x00\x00\x00\x00\x00\x0f\xfc\x20' packed = pack('s5s5', 0x1234, -2, -1.0) self.assertEqual(packed, ref) unpacked = unpack('u19s3f32>', packed) self.assertEqual(unpacked, (0x1234, -2, -1.0)) # least significant byte first ref = b'\x34\x12\x18\x00\x00\xe0\xbc' packed = pack('u19s3f32<', 0x1234, -2, -1.0) self.assertEqual(packed, ref) unpacked = unpack('u19s3f32<', packed) self.assertEqual(unpacked, (0x1234, -2, -1.0)) # least significant byte first ref = b'\x34\x12' packed = pack('u8s8<', 0x34, 0x12) self.assertEqual(packed, ref) unpacked = unpack('u8s8<', packed) self.assertEqual(unpacked, (0x34, 0x12)) # least significant byte first ref = b'\x34\x22' packed = pack('u3u12<', 1, 0x234) self.assertEqual(packed, ref) unpacked = unpack('u3s12<', packed) self.assertEqual(unpacked, (1, 0x234)) # least significant byte first ref = b'\x34\x11\x00' packed = pack('u3u17<', 1, 0x234) self.assertEqual(packed, ref) unpacked = unpack('u3s17<', packed) self.assertEqual(unpacked, (1, 0x234)) # least significant byte first ref = b'\x80' packed = pack('u1<', 1) self.assertEqual(packed, ref) unpacked = unpack('u1<', packed) self.assertEqual(unpacked, (1, )) # least significant byte first ref = b'\x45\x23\x25\x82' packed = pack('u19u5u1u7<', 0x12345, 5, 1, 2) self.assertEqual(packed, ref) unpacked = unpack('u19u5u1u7<', packed) self.assertEqual(unpacked, (0x12345, 5, 1, 2)) def test_performance_mixed_types(self): """Test pack/unpack performance with mixed types. """ print() time = timeit.timeit("pack('s6u7r40b1t152', " "-2, 22, b'\x01\x01\x03\x04\x05', " "True, u'foo fie bar gom gum')", setup="from bitstruct import pack", number=50000) print("pack time: {} s ({} s/pack)".format(time, time / 50000)) time = timeit.timeit( "fmt.pack(-2, 22, b'\x01\x01\x03\x04\x05', " "True, u'foo fie bar gom gum')", setup="import bitstruct ; fmt = bitstruct.compile('s6u7r40b1t152')", number=50000) print("pack time compiled: {} s ({} s/pack)".format(time, time / 50000)) time = timeit.timeit("unpack('s6u7r40b1t152', " "b'\\xf8\\xb0\\x08\\x08\\x18 " "-\\x99\\xbd\\xbc\\x81\\x99" "\\xa5\\x94\\x81\\x89\\x85" "\\xc8\\x81\\x9d\\xbd\\xb4" "\\x81\\x9d\\xd5\\xb4')", setup="from bitstruct import unpack", number=50000) print("unpack time: {} s ({} s/unpack)".format(time, time / 50000)) time = timeit.timeit( "fmt.unpack(b'\\xf8\\xb0\\x08\\x08\\x18 " "-\\x99\\xbd\\xbc\\x81\\x99" "\\xa5\\x94\\x81\\x89\\x85" "\\xc8\\x81\\x9d\\xbd\\xb4" "\\x81\\x9d\\xd5\\xb4')", setup="import bitstruct ; fmt = bitstruct.compile('s6u7r40b1t152')", number=50000) print("unpack time compiled: {} s ({} s/unpack)".format(time, time / 50000)) def test_performance_integers(self): """Test pack/unpack performance with integers. """ print() time = timeit.timeit("pack('s13u7u35u1s9', " "-2, 22, 44567233, 0, 33)", setup="from bitstruct import pack", number=50000) print("pack time: {} s ({} s/pack)".format(time, time / 50000)) time = timeit.timeit( "fmt.pack(-2, 22, 44567233, 0, 33)", setup="import bitstruct ; fmt = bitstruct.compile('s13u7u35u1s9')", number=50000) print("pack time compiled: {} s ({} s/pack)".format(time, time / 50000)) time = timeit.timeit("unpack('s13u7u35u1s9', " "b'\\xff\\xf1`\\x05P\\x15\\x82\\x10\\x80')", setup="from bitstruct import unpack", number=50000) print("unpack time: {} s ({} s/unpack)".format(time, time / 50000)) time = timeit.timeit( "fmt.unpack(b'\\xff\\xf1`\\x05P\\x15\\x82\\x10\\x80')", setup="import bitstruct ; fmt = bitstruct.compile('s13u7u35u1s9')", number=50000) print("unpack time compiled: {} s ({} s/unpack)".format(time, time / 50000)) def test_compile(self): cf = bitstruct.compile('u1u1s6u7u9') packed = cf.pack(0, 0, -2, 65, 22) self.assertEqual(packed, b'\x3e\x82\x16') unpacked = cf.unpack(b'\x3e\x82\x16') self.assertEqual(unpacked, (0, 0, -2, 65, 22)) def test_signed_integer(self): """Pack and unpack signed integer values. """ datas = [ ('s2', 0x01, b'\x40'), ('s3', 0x03, b'\x60'), ('s4', 0x07, b'\x70'), ('s5', 0x0f, b'\x78'), ('s6', 0x1f, b'\x7c'), ('s7', 0x3f, b'\x7e'), ('s8', 0x7f, b'\x7f'), ('s9', 0xff, b'\x7f\x80'), ('s1', -1, b'\x80'), ('s2', -1, b'\xc0') ] for fmt, value, packed in datas: self.assertEqual(pack(fmt, value), packed) self.assertEqual(unpack(fmt, packed), (value, )) def test_unsigned_integer(self): """Pack and unpack unsigned integer values. """ datas = [ ('u1', 0x001, b'\x80'), ('u2', 0x003, b'\xc0'), ('u3', 0x007, b'\xe0'), ('u4', 0x00f, b'\xf0'), ('u5', 0x01f, b'\xf8'), ('u6', 0x03f, b'\xfc'), ('u7', 0x07f, b'\xfe'), ('u8', 0x0ff, b'\xff'), ('u9', 0x1ff, b'\xff\x80') ] for fmt, value, packed in datas: self.assertEqual(pack(fmt, value), packed) self.assertEqual(unpack(fmt, packed), (value, )) def test_bad_float_size(self): """Test of bad float size. """ with self.assertRaises(ValueError) as cm: pack('f31', 1.0) self.assertEqual(str(cm.exception), 'expected float size of 16, 32, or 64 bits (got 31)') with self.assertRaises(ValueError) as cm: unpack('f33', 8 * b'\x00') self.assertEqual(str(cm.exception), 'expected float size of 16, 32, or 64 bits (got 33)') def test_bad_format(self): """Test of bad format. """ formats = [ ('g1', "bad char 'g' in format"), ('s1u1f32b1t8r8G13', "bad char 'G' in format"), ('s1u1f32b1t8r8G13S3', "bad char 'G' in format"), ('s', "bad format 's'"), ('1', "bad format '1'"), ('ss1', "bad format 'ss1'"), ('1s', "bad format '1s'"), ('foo', "bad format 'foo'"), ('s>1>', "bad format 's>1>'") ] for fmt, expected_error in formats: with self.assertRaises(ValueError) as cm: bitstruct.compile(fmt) self.assertEqual(str(cm.exception), expected_error) def test_empty_format(self): """Test of empty format type. """ cf = bitstruct.compile('') self.assertEqual(cf.pack(), b'') self.assertEqual(cf.pack(1), b'') self.assertEqual(cf.unpack(b''), ()) self.assertEqual(cf.unpack(b'\x00'), ()) def test_byte_order_format(self): """Test of a format with only byte order informationx. """ cf = bitstruct.compile('>') self.assertEqual(cf.pack(), b'') self.assertEqual(cf.pack(1), b'') self.assertEqual(cf.unpack(b''), ()) self.assertEqual(cf.unpack(b'\x00'), ()) if __name__ == '__main__': unittest.main() bitstruct-3.7.0/tests/__init__.py0000664000175000017500000000000012760401517016720 0ustar erikerik00000000000000