2017-03-01 1 views
2

저는 Python을 처음 접했습니다. 내가 뭘하고 싶은지 바이너리 파일에서 C와 같은 구조체를 읽는 것이다. 구조체는, 그것들을 생성하는 C 프로그램에서 다음과 같이 정의된다 :복잡한 데이터 구조 Numpy

struct B{ 
    uint16 y; 
    uint8 c[SIZE2]; 
} 

struct A{ 
    uint32 x; 
    struct B b[SIZE1]; 
} 

내가 NumPy와 패키지 기능 fromFile를 사용하여 모든 A-구조체를 읽을 수 있도록하고 싶습니다,하지만 난 방법을 호출 할 생각이 없다 적절한 dtype 방법 :

record = numpy.dtype([ 
    ("field1", numpy.uint8), 
    ("field2", numpy.uint16), 
    ("field3", numpy.uint32) 
]) 

복잡한 데이터 구조.

저에게 도움을 주시기 바랍니다. 미리 감사드립니다.

+0

[여기] (https://docs.scipy.org/doc/numpy-1.10.1/user/basics.rec.html)를 보았습니까? 나는 네가 그처럼 둥지를 틀어 놓을 수 있을지 확신하지 못한다. 또한 아마도 [이 질문] (http://stackoverflow.com/questions/9909399/nested-structured-numpy-array)과 관련이 있습니다. 확실하지 않습니다. –

답변

1

이것은 C 구조체를 많이 사용하지 않았기 때문에 추측입니다. 이 정의에서

In [125]: SIZE1, SIZE2 = 3,4 

In [127]: dtB=np.dtype([('y',np.uint16),('c',np.uint8,(SIZE2,))]) 
In [128]: np.ones((2,), dtype=dtB) 
Out[128]: 
array([(1, [1, 1, 1, 1]), (1, [1, 1, 1, 1])], 
     dtype=[('y', '<u2'), ('c', 'u1', (4,))]) 
In [129]: _.itemsize 
Out[129]: 6 

이 배열의 각각의 레코드는 6 바이트의 c 필드 2 y 필드, 4 구성된다. A 정의

In [130]: dtA=np.dtype([('x',np.uint32),('b',dtB,(SIZE1,))]) 
In [131]: np.ones((2,), dtype=dtA) 
Out[131]: 
array([(1, [(1, [1, 1, 1, 1]), (1, [1, 1, 1, 1]), (1, [1, 1, 1, 1])]), 
     (1, [(1, [1, 1, 1, 1]), (1, [1, 1, 1, 1]), (1, [1, 1, 1, 1])])], 
     dtype=[('x', '<u4'), ('b', [('y', '<u2'), ('c', 'u1', (4,))], (3,))]) 
In [132]: _.itemsize 
Out[132]: 22 

각 레코드는 4 x 필드의 바이트 3 개 b 요소 3 * 6을 갖는 그런

둥지.

In [133]: __.tobytes() 
Out[133]: b'\x01\x00\x00\x00\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01\x01\x00\x00\x00\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01\x01\x00\x01\x01\x01\x01' 

그리고 배열 더 재미있게 만들려고 노력 :
In [136]: A['x']=[1,2] 
In [139]: A['b']['y'] *= 3 
In [141]: A['b']['c'][0]=2 
In [142]: A['b']['c'][1]=3 
In [143]: A 
Out[143]: 
array([(1, [(3, [2, 2, 2, 2]), (3, [2, 2, 2, 2]), (3, [2, 2, 2, 2])]), 
     (2, [(3, [3, 3, 3, 3]), (3, [3, 3, 3, 3]), (3, [3, 3, 3, 3])])], 
     dtype=[('x', '<u4'), ('b', [('y', '<u2'), ('c', 'u1', (4,))], (3,))]) 
In [144]: A[0].tobytes() 
Out[144]: b'\x01\x00\x00\x00\x03\x00\x02\x02\x02\x02\x03\x00\x02\x02\x02\x02\x03\x00\x02\x02\x02\x02' 

그 bytestrings이 c 구조체와 일치?

+0

완벽하게 작동했습니다. 고맙습니다! – neekogi