2015-04-24 30 views
1

我一直在嘗試用包裝一個字節的基礎上,我的最後一個問題變化值,一些位現場:Field packing to form a single byte現場包裝字節返回意外的結果

不過,我基礎上,我得到意想不到的結果值。頂部的代碼示例給我的0x91預期的輸出,但如果我改變colorResolutionsizeOfGlobalColorTable變量:010,我得到的0x80意想不到的輸出,是不是它應該是什麼樣的二進制表示:10100010從這裏開始的:http://www.best-microcontroller-projects.com/hex-code-table.html 。我期望底部代碼示例的輸出爲:0xA2。我錯過了什麼或不理解?

此代碼正確地記錄:0x91

uint8_t screenDescriptorPackedFieldByte = 0; 

uint8_t globalColorTableFlag = 1; 
uint8_t colorResolution = 001; 
uint8_t screenDescriptorSortFlag = 0; 
uint8_t sizeOfGlobalColorTable = 001; 

screenDescriptorPackedFieldByte |= ((globalColorTableFlag & 0x1) << 7); 
screenDescriptorPackedFieldByte |= ((colorResolution & 0x7) << 4); 
screenDescriptorPackedFieldByte |= ((screenDescriptorSortFlag & 0x1) << 3); 
screenDescriptorPackedFieldByte |= ((sizeOfGlobalColorTable & 0x7) << 0); 

NSLog(@"0x%02X",screenDescriptorPackedFieldByte); 

此代碼錯誤地記錄:0x80

uint8_t screenDescriptorPackedFieldByte = 0; 

uint8_t globalColorTableFlag = 1; 
uint8_t colorResolution = 010; 
uint8_t screenDescriptorSortFlag = 0; 
uint8_t sizeOfGlobalColorTable = 010; 

screenDescriptorPackedFieldByte |= ((globalColorTableFlag & 0x1) << 7); 
screenDescriptorPackedFieldByte |= ((colorResolution & 0x7) << 4); 
screenDescriptorPackedFieldByte |= ((screenDescriptorSortFlag & 0x1) << 3); 
screenDescriptorPackedFieldByte |= ((sizeOfGlobalColorTable & 0x7) << 0); 

NSLog(@"0x%02X",screenDescriptorPackedFieldByte); 

回答

4

此值不是二進制。它是octal

uint8_t sizeOfGlobalColorTable = 010; 

(Objective) C常數從0開始被解釋爲八進制值。你實際上寫的是b1000 & b0111 = 0

它應該是:

uint8_t sizeOfGlobalColorTable = 0x2; 
+0

我不希望使用十六進制值作爲輸入,我想使用0或1作爲我的標誌。 – klcjr89

+0

@ aviatorken89就我在Google看到的,Objective-C中沒有二進制文字,所以你必須處理它。在使用Hex的時候會給你工作代碼。 – Alex

+0

或者我可以刪除前導零,一切都會好?這對我來說很好,如果這樣做會產生有效的字節。 – klcjr89

0

用C 010是用於小數8.

前導0使得編譯器假定要一個八進制值,類似於使用八進制(基數8) 0x前綴表示十六進制。

這將(正確)導致0和0的位計算行2 & 4。 您只想消除010的開頭0或10或十進制010,0x10。

+0

那麼對於帶前導零的標誌,我可以安全地刪除前導零? – klcjr89

+0

在你的代碼的情況下,001和小數點1一樣,所以你可以刪除前導零。 – hansmuff

+0

我想我只是明白你的問題。如果您打算爲您的數字/標誌使用十六進制,請使用前導0x並且不需要十六進制值中的前導零。 – hansmuff