2015-05-04 47 views
1

我試圖用C手動讀取和打開一個BMP文件,並且在閱讀了BMP規範並瞭解這些文件的工作方式後,頭文件中的字節定義等於bfOffBitsbiWidth 。因此,例如bfOffBits等於4個字節,在我的測試位圖中是'8A 04 00 00'。我從這裏到達圖像的偏移量數據的十進制等效數值究竟如何?如何計算bfOffBits

我非常,非常到C新這樣的語言是如何工作的概念是我考慮到我工作的主要語言是PHP非常不同的,這樣下去我很容易:)

目前,我我通過在C這感覺完全錯了此功能,但被排序的工作了一段偏移值,而不是其他的偏移值

int calculateBytes(int bytes[4]) { 
    int Value = bytes[0]; 
    if (bytes[1] > 0) { 
     if (bytes[0] == 0) { 
      Value = 256; 
     } 
     Value = Value * bytes[1]; 
    } 
    if (bytes[2] > 0) { 
     if (bytes[1] == 0) { 
      if (bytes[0] == 0) { 
       Value = 256; 
      } 
      Value = Value * 256; 
     } 
     Value = Value * bytes[2]; 
    } 
    if (bytes[3] > 0) { 
     if (bytes[2] == 0) { 
      if (bytes[1] == 0) { 
       if (bytes[0] == 0) { 
        Value = 256; 
       } 
       Value = Value * 256; 
      } 
      Value = Value * 256; 
     } 
     Value = Value * bytes[3]; 
    } 
    return Value; 
} 

回答

3

你可以這樣做只是這樣的:

char bytes[] = {0x8A, 0x04, 0x00, 0x00}; 
int* p_int = (int*)bytes; // Unsafe version ,doesn't take into account endianness 
int num2 = bytes[0] | ((int)bytes[1] << 8) | ((int)bytes[2] << 16) | ((int)bytes[3] << 24); // Safe version 
printf("%d %d\n", *p_int, num2); 

因此,您的功能如下所示:

int calculateBytes(int bytes[4]) { 
    int num = bytes[0] 
       | ((int)bytes[1] << 8) 
       | ((int)bytes[2] << 16) 
       | ((int)bytes[3] << 24); 
    return num; 
} 
+0

啊這個工作!非常容易理解,謝謝! –

2

發佈值'8A 04 00 00'看起來像'little Endian'。

是您使用'小Endian'的建築。如果是這樣,只需將該值讀入一個int。否則,顛倒4個字節的順序。然後用類似printf的結果值:printf(「offset:%d \ n」,myInt);


一個簡單的方法來「小尾數」轉換爲「大端」在32​​位架構。

int convert(char *pBytes) 
{ 
    int result = 0; 
    result = pBytes[3]; 
    result <<= 8; 
    result += pBytes[2]; 
    result <<= 8; 
    result += pBytes[1]; 
    result <<= 8; 
    result += pBytes[0]; 
    return(result); 
} // end function: convert 
+0

謝謝!我也明白這一點,但看起來你一分鐘太短 –