How to determine 'word' size in Python

后端 未结 6 473
再見小時候
再見小時候 2021-01-20 00:03

I need to know the number of bytes in a \'word\' in Python. The reason I need this is I have the number of words I need to read from a file; if I knew the number of bytes in

6条回答
  •  情歌与酒
    2021-01-20 00:32

    There's no really sound definition for what a word is; except that certain archetectures call some number of bytes 'word' (x86 calls 2 bytes a word, PPC calls 4 bytes a word), but there's not much significance besides this arbitrary value.

    Perhaps the simplest solution is to just defer to the struct module; for instance, the format 'h' means signed short (which reasonably agrees with the intel definition of 'word'). So you could do this:

    >>> import struct
    >>> f = file('.vimrc')
    >>> struct.unpack('h', f.read(struct.calcsize('h')))
    (8226,)
    >>> 
    

提交回复
热议问题