Welcome to the Pycom forum Forum
    • \[\[global:header.categories\]\]
    • \[\[global:header.recent\]\]
    • \[\[global:header.tags\]\]
    • \[\[global:header.popular\]\]
    • Login

    Explore Pybytes | Official Documentation | Report a Firmware Bug/Issue | GitHub

    struct

    Scheduled Pinned Locked Moved GPy
    3 Posts 2 Posters 33 Views 2 Watching
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • K Offline
      kjm
      last edited by kjm

      If I convert a character to bytes I get 1 byte

      >>> bytes=struct.pack('s', 'F'); print(bytes, len(bytes))
      b'F' 1
      

      If I convert an epoch to bytes I get 4 bytes

      >>> bytes=struct.pack('I', 1611017052); print(bytes, len(bytes))
      b'\\+\x06`' 4
      

      How come when I do both together I get 8 instead of 4+1=5 ??

      bytes=struct.pack('sI', 'F', 1611017052); print(bytes, len(bytes))
      b'F\x00\x00\x00\\+\x06`' 8
      

      but this way I get the 5 I expect?

      >>> bytes=struct.pack('Is', 1611017052, 'F'); print(bytes, len(bytes))
      b'\\+\x06`F' 5
      
      

      why is a different packing sequence giving different numbers of bytes?

      1 Reply Last reply Reply Quote 0
      • G Offline
        Gijs
        last edited by Gijs

        This is related to the byte-alignment in struct, aligning to the longest used data type. As I is 4 bytes long, and s is 1 byte, the total length of the structure will be either 5 or 8, depending on the alignment. As you put sI, we would expect the character on the first index, and the integer on the second index, however, the controller knows these integers take 4 bytes, and expects the integer to start on the 5th index, as the 1st index already contains a character, therefor you get 3 null bytes after the character. This is expected behaviour

        You can disable the alignment with an < or > sign in the type definition

        K 1 Reply Last reply Reply Quote 3
        • K Offline
          kjm @Gijs
          last edited by

          @Gijs tnx

          1 Reply Last reply Reply Quote 0

          Hello! It looks like you're interested in this conversation, but you don't have an account yet.

          Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.

          With your input, this post could be even better 💗

          Register Login
          • 1 / 1
          • First post
            Last post

          Pycom on Twitter

          Pycom