久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

在 Python 中從二進制文件中讀取整數

Reading integers from binary file in Python(在 Python 中從二進制文件中讀取整數)
本文介紹了在 Python 中從二進制文件中讀取整數的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我正在嘗試用 Python 讀取 BMP 文件.我知道前兩個字節表示 BMP 公司.接下來的 4 個字節是文件大小.當我執行時:

I'm trying to read a BMP file in Python. I know the first two bytes indicate the BMP firm. The next 4 bytes are the file size. When I execute:

fin = open("hi.bmp", "rb")
firm = fin.read(2)  
file_size = int(fin.read(4))  

我明白了:

ValueError: int() 以 10 為底的無效文字:'F#x13'

ValueError: invalid literal for int() with base 10: 'F#x13'

我想要做的是將這四個字節作為整數讀取,但似乎 Python 正在將它們作為字符讀取并返回一個字符串,該字符串無法轉換為整數.我怎樣才能正確地做到這一點?

What I want to do is reading those four bytes as an integer, but it seems Python is reading them as characters and returning a string, which cannot be converted to an integer. How can I do this correctly?

推薦答案

read 方法將字節序列作為字符串返回.要將字符串字節序列轉換為二進制數據,請使用內置 struct 模塊:http://docs.python.org/library/struct.html.

The read method returns a sequence of bytes as a string. To convert from a string byte-sequence to binary data, use the built-in struct module: http://docs.python.org/library/struct.html.

import struct

print(struct.unpack('i', fin.read(4)))

請注意,unpack 總是返回一個元組,所以 struct.unpack('i', fin.read(4))[0] 給出了你所需要的整數值正在追趕.

Note that unpack always returns a tuple, so struct.unpack('i', fin.read(4))[0] gives the integer value that you are after.

您可能應該使用格式字符串 '<i'(< 是指示小端字節序和標準大小和對齊方式的修飾符 - 默認是使用平臺的字節順序、尺寸和對齊方式).根據 BMP 格式規范,字節應按 Intel/little-endian 字節順序寫入.

You should probably use the format string '<i' (< is a modifier that indicates little-endian byte-order and standard size and alignment - the default is to use the platform's byte ordering, size and alignment). According to the BMP format spec, the bytes should be written in Intel/little-endian byte order.

這篇關于在 Python 中從二進制文件中讀取整數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How to draw a rectangle around a region of interest in python(如何在python中的感興趣區域周圍繪制一個矩形)
How can I detect and track people using OpenCV?(如何使用 OpenCV 檢測和跟蹤人員?)
How to apply threshold within multiple rectangular bounding boxes in an image?(如何在圖像的多個矩形邊界框中應用閾值?)
How can I download a specific part of Coco Dataset?(如何下載 Coco Dataset 的特定部分?)
Detect image orientation angle based on text direction(根據文本方向檢測圖像方向角度)
Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 檢測圖像中矩形的中心和角度)
主站蜘蛛池模板: 一级免费看 | 亚洲一区国产 | 日韩精品a在线观看图片 | 国产一区二区不卡 | 久久一级大片 | 免费观看成人性生生活片 | 国产一区二区三区在线 | 人人九九精 | 亚洲欧美激情精品一区二区 | 黄色精品| 一区二区三区免费 | 黄色小视频大全 | 一区二区在线免费观看视频 | 亚洲在线一区二区三区 | 1区2区3区视频 | 国产激情 | 国产在线一区二区三区 | 欧美精品一区二区三区在线四季 | 国产重口老太伦 | 亚洲免费在线观看 | 在线播放精品视频 | www久久国产 | 久久久片| 久草新在线 | 天天干天天爽 | 日韩电影中文字幕 | 久久久女女女女999久久 | 91久操网 | 成人精品一区二区三区 | 一区二区在线不卡 | 夜夜夜操 | 91人人在线 | 亚洲一区二区三区四区五区中文 | 精品91久久| 亚洲视频中文字幕 | 伊人在线视频 | 国产成人精品免费视频大全最热 | av国产精品 | 日韩一级电影免费观看 | 美女视频黄色片 | 性欧美精品一区二区三区在线播放 |