[問題] unsigned int bitwise operator

看板C_and_CPP作者時間6年前 (2018/05/14 00:30), 編輯推噓3(304)
留言7則, 5人參與, 6年前最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) Lubuntu (Linux) 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) GCC 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) n/a 問題(Question): 大家好,新手自學 #include <stdio.h> #include <stdlib.h> int main(){ unsigned int a = 10; signed int b = 10; a = ~a; b = ~b; printf("a : %d\n"); printf("b : %d]n"); } output : a = -11 b = -11 這邊的問題是有關於 a a = 10 , in bit 應該是 00000000 00000000 00000000 00001010 a = ~a 之後 11111111 11111111 11111111 11110101 ^ not sign bit 我這邊一開始設定 a 是 unsigned int 也就是應該第 32 bit 應該不是 sign bit 所以 print out in %d 之後預期的結果應該是 unsigned int 的 最大值 - 10 可是為什麼變成了 -11 再請各位前輩解惑了 謝謝 餵入的資料(Input): 資料如上 預期的正確結果(Expected Output): 預期為 unsigned int 最大值 - 11 錯誤結果(Wrong Output): no error code 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) code 如上 補充說明(Supplement): n/a -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 42.72.62.242 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1526229056.A.C47.html

05/14 00:36, 6年前 , 1F
%u
05/14 00:36, 1F

05/14 00:36, 6年前 , 2F
%d 造成的唷。改%u
05/14 00:36, 2F

05/14 00:40, 6年前 , 3F
你可以查printf的文件
05/14 00:40, 3F

05/14 11:37, 6年前 , 4F
資料長那樣沒錯,不過解讀的方法錯了
05/14 11:37, 4F

05/14 19:43, 6年前 , 5F
你是不是在找2補數?
05/14 19:43, 5F

05/14 21:04, 6年前 , 6F
剛剛才發現一件事情,你預期的正確結果應該是-10吧?
05/14 21:04, 6F

05/14 21:04, 6年前 , 7F
你好像寫成-11了
05/14 21:04, 7F
文章代碼(AID): #1Q-6X0n7 (C_and_CPP)