推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
hnsxyhh
V2EX  ›  Python

为什么打印出来的长度不一样呢??

  •  
  •   hnsxyhh · Aug 27, 2015 · 3157 views
    This topic created in 3920 days ago, the information mentioned may be changed or developed.
    import struct

    s = struct.Struct ('Is')
    s1 = struct.Struct ('sI')

    print ("s.size:",s.size )
    print ("s1.size:",s1.size )

    ################
    运行结果:
    s.size: 5
    s1.size: 8
    4 replies    2015-08-27 23:20:04 +08:00
    wartime
        1
    wartime  
       Aug 27, 2015
    int 类型在内存中存放地址 4 字节对齐, 导致 s1 占了额外空间.

    s.pack (1, 'a')
    '\x01\x00\x00\x00a'

    s1.pack ('a', 1 )
    'a\x00\x00\x00\x01\x00\x00\x00'

    可以看到内存中实际存放方式
    hnsxyhh
        2
    hnsxyhh  
    OP
       Aug 27, 2015
    @wartime 为什么 s1 有对齐, s 没有对齐啊
    exch4nge
        3
    exch4nge  
       Aug 27, 2015
    @hnsxyhh 可以去了解了解 C/C++的结构体对齐,就大概知道为啥 python 这个也要对齐了
    wartime
        4
    wartime  
       Aug 27, 2015   ❤️ 1
    @hnsxyhh s 的起始地址是四字节对齐的,首先存放 int 类型值,就不需要再偏移, s1 里起始地址存放的是一个 char 类型,占用一个字节,假设是 s1 起始地址是 0x1000, int 存放地址就是从 0x1001 开始,没有对齐, 只有再偏移三个字节, 到 0x1004, 才能四字节对齐。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1394 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 17:12 · PVG 01:12 · LAX 10:12 · JFK 13:12
    ♥ Do have faith in what you're doing.