Commits

Benjamin Peterson  committed 9beb723

add byte2int (fixes #26)

  • Participants
  • Parent commits 7bba99a

Comments (0)

Files changed (4)

 Development version
 -------------------
 
+- Issue #26: Add byte2int function which complements int2byte.
+
 - Add a PY2 constant with obvious semantics.
 
 - Add helpers for indexing and iterating over bytes: iterbytes and indexbytes.

File documentation/index.rst

    equivalent to :func:`py2:chr` in Python 2 and ``bytes((i,))`` in Python 3.
 
 
+.. function:: byte2int(bs)
+
+   Converts the first byte of *bs* to an integer.  This is equivalent to
+   ``ord(bs[0])`` on Python 2 and ``bs[0]`` on Python 3.
+
+
 .. function:: indexbytes(buf, i)
 
    Return the byte at index *i* of *buf* as an integer.  This is equivalent to
     else:
         # This is about 2x faster than the implementation above on 3.2+
         int2byte = operator.methodcaller("to_bytes", 1, "big")
+    byte2int = operator.itemgetter(0)
     indexbytes = operator.getitem
     iterbytes = iter
     import io
     def u(s):
         return unicode(s, "unicode_escape")
     int2byte = chr
+    def byte2int(bs):
+        return ord(bs[0])
     def indexbytes(buf, i):
         return ord(buf[i])
     def iterbytes(buf):
     py.test.raises((OverflowError, ValueError), six.int2byte, 256)
 
 
+def test_byte2int():
+    assert six.byte2int(six.b("\x03")) == 3
+    assert six.byte2int(six.b("\x03\x04")) == 3
+    py.test.raises(IndexError, six.byte2int, six.b(""))
+
+
 def test_bytesindex():
     assert six.indexbytes(six.b("hello"), 3) == ord("l")