簡體   English   中英

從二進制文件讀取字節

[英]Reading bytes from a binary file

我有一個二進制文件,我需要從( x, y )位置z存儲字節數。 例如,我有以下字節序列:

00000000  49  49  49  49  05  00  00  00   08  00  00  00  1a  00  00  00 | y0 
00000010  39  a6  82  f8  47  8b  b8  10   78  97  f1  73  56  d9  6f  00 | y1
00000020  58  99  d5  3b  ac  7b  7b  40   b6  2e  9f  0a  69  b2  ac  a0 | y2
          ________________________________________________________________
          x0  x1  x2  x3  x4  x5  x6  x7   x8  x9  x10 x11 x12 x13 x14 x15

每2個合並的數字表示1個字節(它取自hexdump -C-編碼為一點endian)。 49 = 1個字節, f8是1個字節, f8 ...

( x , y )表示位置。 例如,如果我把x = 2,y = 2,我得到位置( 2, 2 ) ,這意味着我開始從位置y2,x2讀取字節。 在這種情況下,我從字節d5開始。如果我輸入z = 3 ,則意味着我想在這種情況下存儲3個字節,這些字節是d5, 3b, ac

我可以通過一個簡單的公式計算位置:

position = 16 * y + x  
position = 16 * 2 + 2    // i put x = 2, y = 2 to formula
position = 34    // get number 34, that means i will start storing at 35th byte in this case it's d5
binaryFile . seekg ( position )  // jump to position in a file ( itc it's 99 )
binaryFile . read ( ( char * )&dest, z )) // save z bytes

如果我將z = 3放進去,我將存儲3個字節: d5, 3b, ac

但是somtimes系數z , x , y不是整數:

如果我把y = 2, x = 1,5 and z = 3 // ( 1,5, 2 )這意味着我必須跳到不是99字節,而是d5然后在這種情況下存儲2個字節d5 , 3b並加到它們是字節99一半字節,字節ac一半字節,因為起始位置是x = 1,5 我該怎么辦?

您必須在兩端擴展到字節邊界,然后首先讀取要寫入的區域。 因此,如果要寫入兩個字節,則必須讀取三個字節。

然后,您將必須進行適當的位移位和屏蔽,以將位放置在正確的位置。

例如,如果您要寫兩個移位了½個字節的字節,則應從以下內容開始:

unsigned char *mydata = MyDataToWrite();
unsigned char temp[bigEnough];
binaryFile.input(temp, 3);
temp[0] = (temp[0] & 0xf0) | (mydata[0] >> 4);
// more code here to put bits in temp
binaryFile.output(temp, 3);

將數據放入temp ,將3個字節寫回到讀取的相同位置。

我不會在這里寫整個內容,但我希望這能給您一個思路,您可以從

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM