Page 158 - Programming With Python 3
P. 158

An Introduction to STEM Programming with Python — 2019-09-03a                              Page 145
            Chapter 12 — String Encoding



                               Example:
             Free
                               4350 is 0001000011111110 in binary and 10FE in hexadecimal.

                               b"\x10\xfe" is big-endian and
                               b"\xfe\x10" is little-endian

             eBook
            The method to_bytes requires two arguments, The first is the width in bytes and the second is how to
            encode the bytes. The second method from_bytes takes a collection of bytes, how it was ordered, and
            will return an integer.

               1|  a = 8853778
               2|
             Edition
               3|  # converting an integer to a "big-endian" collection of bytes
               4|  b = a.to_bytes(4, byteorder='big')
               5|  print(b)
               6|  print(int.from_bytes(b, byteorder='big'))
               7|
            Please support this work at
               8|  # converting an integer to a "little-endian" collection of bytes
               9|  b = a.to_bytes(4, byteorder='little')
             10|  print(b)
             11|  print(int.from_bytes(b, byteorder='little'))
                                  http://syw2l.org
                    b'\x00\x87\x19\x12'
                    8853778
                    b'\x12\x19\x87\x00'
                    8853778                                                    Free


            Summary


                                                                   eBook
            Goes here


            Important Terms



            here
                                                                Edition








            Copyright 2019 — James M. Reneau Ph.D. — http://www.syw2l.org — This work is licensed
            under a Creative Commons Attribution-ShareAlike 4.0 International License.
   153   154   155   156   157   158   159   160   161   162   163