簡體   English   中英

從二進制文件讀取6字節8位整數

[英]Reading 6 byte 8-bit integer from binary file

這是我的文件的樣子:

00 00 00 00 00 34 ....

我已經使用fread將其讀取到unsigned char數組中,但是我不知道如何將其轉換為unsigned integer 該數組如下所示:

0, 0, 0, 0, 0, 52

這就是我的工作方式:

unsigned char table_index[6];
fread(table_index, 1, 6, file);

unsigned long long tindex = 0;
tindex = (tindex << 8);
tindex = (tindex << 8);
tindex = (tindex << 8) + table_index[0];
tindex = (tindex << 8) + table_index[1];
tindex = (tindex << 8) + table_index[2];
tindex = (tindex << 8) + table_index[3];
tindex = (tindex << 8) + table_index[4];
tindex = (tindex << 8) + table_index[5];

您從48位值開始,但是系統上可能沒有48位整數類型。 但是可能有64位類型,並且可能是“長長”類型。

假設您的6個字節排在最前面,並且理解您需要長時間填寫兩個額外的字節,則可以執行以下操作:

long long myNumber;
char *ptr = (char *)&myNumber;
*ptr++ = 0; // pad the msb
*ptr++ = 0; // pad the 2nd msb

fread(ptr, 1, 6, fp);

現在,您在myNumber有了一個值

如果文件充滿了48位整數(例如我假設您正在談論的內容),則可以從char數組中執行以下操作:

char temp[8];
unsigned char *data = //...
unsigned char *data_ptr = data;
vector<unsigned long long> numbers;

size_t sz = // Num of 48-bit numbers
for (size_t i = 0; i < sz; i++, data_ptr += 6)
{
   memcpy(temp + 2, data_ptr, 6);

   numbers.push_back((unsigned long long)*temp);
}

該算法假定數字均已在文件中正確編碼。 它還假定我不能說出我的頭名。

如果要將uchar數組的4個字節解釋為一個uint,請執行以下操作:

unsigned char uchararray[totalsize];
unsigned int * uintarray = (unsigned int *)uchararray;

如果您希望將uchar數組的一個字節轉換為一個uint,請執行以下操作:

unsigned char uchararray[totalsize];
unsigned int uintarray[totalsize];

for(int i = 0 ; i < totalsize; i++)
    uintarray[i] = (unsigned int)uchararray[i];

這是你在說什么嗎?

// long long because it's usually 8 bytes (and there's not usually a 6 byte int type)
vector<unsigned long long> numbers;
fstream infile("testfile.txt");

if (!infile) {
    cout << "fail" << endl;
    cin.get();
    return 0;
}

while (true) {
    stringstream numstr;
    string tmp;
    unsigned long long num;

    for (int i = 0; i < 6 && infile >> tmp; ++i)
        numstr << hex << tmp;

    if (cin.bad())
        break;

    cout << numstr.str() << endl;
    numstr >> num;
    numbers.push_back(num);
}

我用您提供的輸入( 00 00 23 51 A4 D2 )對其進行了測試,向量的內容為592553170

暫無
暫無

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

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