在python中使用字节

2024-09-30 01:22:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着把a端口处理.org应用到python中并有一些困难。在

我需要用python编写:

int[][] elevation; // elevations in meters
float[][] felevation; // scaled to range [0,1] where 1=max
int maxheight;

void setup(){
size(600,600,P2D);

// read srtm binary file
elevation=new int[1201][1201];
felevation=new float[1201][1201];
byte b[] = loadBytes("N30W091.hgt"); // THIS IS A BINARY FILE
int ix=0;
maxheight=0;
for (int row=0;row<1201;row++) {
  for (int col=0;col<1201;col++) {
    // bytes are signed, from -128 to 127, converts to unsigned...
    int hi = b[ix] & 0xff; 
    int lo = b[ix+1] & 0xff; 
    int el=(int)((hi<<8)|lo); // big endian!
    elevation[row][col]=el;
    if (el>maxheight && el<32000) maxheight=el; 
    ix+=2;
   }
}

。。。等等

到目前为止,我所做的是:

^{pr2}$

我总是

Traceback (most recent call last):

  File "C:\Users\CNA\workspace\Revitter\PatternAsignment.py", line 16, in <module>

TypeError: unsupported operand type(s) for +: 'str' and 'int'

有什么想法吗。。我是python新手,我没有处理字节的经验。。。在


Tags: toinlonewforcolhifloat
3条回答

我不确定是否有.respeme语法正确(将进一步测试)-但类似这样的东西应该可以满足您的需要:

import numpy

def readHgtFile(fname, h=1201, w=1201):
    with open(fname, 'rb') as inf:
        return numpy.fromfile(inf, dtype=[('height', '>u2')], count=h*w).reshape((h,w))

def main():
    elevation = readHgtFile('N30W091.hgt')
    maxheight = elevation.max()

if __name__=="__main__":
    main()

在Python中,'hello'[2]也是字符串(在本例中=='l')。您需要使用ord将它们转换为整数,并使用chr将它们转换回字符串。在

elevation = [[],[]]
maxheight=0

b = open("C:\\Users\\CNA\\sketchbook\\_SRTM\\data\\N59E010.hgt","rb")
fin = b.read() # you probably need to read more than 1 byte, this will read whole file
print(len(fin))
ix = 0
for row in range(0,1201):
    for col in range(0,1201):
        hi = (ord(fin[ix])   + 0xff) # ord returns unsigned integer, so you probably don't need to convert it
        lo = (ord(fin[ix+1]) + 0xff)
        el = (hi << 8) | lo

参见:http://docs.python.org/library/functions.html

一个惯用的翻译方法是完全不同的。在

在原始代码中,您需要执行一系列位旋转,将两个字节值转换为单个数值。{cd1>内置了Python}功能。事实证明,这个模块是为一次读取多个值而构建的。在

另外,对文件名使用正斜杠-这样更容易,而且可以保证工作。为了保证列表的完整性和完整性,请使用Python来自动停止列表和列表的构建。在

这给了我们:

import struct
with open('C:/Users/CNA/sketchbook/_SRTM/data/N59E010.hgt', 'rb') as data:
    elevation = [
        list(struct.unpack('>1201H', data.read(1201 * 2)))
        for row in range(1201)
    ]
maxheight = max(max(cell for cell in row if cell < 32000) for row in elevation)

你就完蛋了。欢迎使用Python:)

相关问题 更多 >

    热门问题