首页
注册
登录
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请
登录
推荐学习书目
›
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
V2EX
›
Python
为什么打印出来的长度不一样呢??
hnsxyhh
·
2015-08-27 14:30:38 +08:00
· 2416 次点击
这是一个创建于 3325 天前的主题,其中的信息可能已经有所发展或是发生改变。
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
struct
print
import
s.si
4 条回复
•
2015-08-27 23:20:04 +08:00
1
wartime
2015-08-27 14:44:49 +08:00
int 类型在内存中存放地址 4 字节对齐, 导致 s1 占了额外空间.
s.pack (1, 'a')
'\x01\x00\x00\x00a'
s1.pack ('a', 1 )
'a\x00\x00\x00\x01\x00\x00\x00'
可以看到内存中实际存放方式
2
hnsxyhh
OP
2015-08-27 17:31:14 +08:00
@
wartime
为什么 s1 有对齐, s 没有对齐啊
3
exch4nge
2015-08-27 17:34:54 +08:00
@
hnsxyhh
可以去了解了解 C/C++的结构体对齐,就大概知道为啥 python 这个也要对齐了
4
wartime
2015-08-27 23:20:04 +08:00
1
@
hnsxyhh
s 的起始地址是四字节对齐的,首先存放 int 类型值,就不需要再偏移, s1 里起始地址存放的是一个 char 类型,占用一个字节,假设是 s1 起始地址是 0x1000, int 存放地址就是从 0x1001 开始,没有对齐, 只有再偏移三个字节, 到 0x1004, 才能四字节对齐。
关于
·
帮助文档
·
博客
·
API
·
FAQ
·
实用小工具
·
2023 人在线
最高记录 6679
·
Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 26ms ·
UTC 14:39
·
PVG 22:39
·
LAX 07:39
·
JFK 10:39
Developed with
CodeLauncher
♥ Do have faith in what you're doing.