Re: [問題] C語法轉Python

看板Python作者 (←這人是超級笨蛋)時間13年前 (2012/11/26 21:17), 編輯推噓4(407)
留言11則, 4人參與, 最新討論串2/2 (看更多)
※ 引述《blackspace98 (~我愛夏天~)》之銘言:

11/26 20:38,
(int(buf[3]<<8)) + (int(buf[4])) 失敗XD
11/26 20:38
應該是可以跑吧, 只是出來的結果不對 Python 的 int 範圍和 C 不一樣(有興趣的話可以用 sys.maxint 和 minint 看) 而且我沒記錯的話這個值是 implementation dependent, 不是規範 所以你在把 C 的位元運算轉換到 Python 時必須注意這個問題 假設你原本 C 語言的 int 是 16-bit (說到這個, 你原本那個實作有問題, 因為 int 的範圍在各平台不一定一樣 在這種狀況應該用 intXX_t 系列的型別比較好, 參見 http://goo.gl/15MI5 而且用有號型別做位元運算實在太容易出包了, 建議改用無號) 那麼你必須在左移後把 0x100 以上的位數 mask 掉 例如像這樣 int((buf[3] << 8) & 0xffff) + int(buf[4]) 才會得到你預期的結果 -- Les grandes et les meilleurs tone from "Zadok the Priest" Eine grosse stattliche Veranstaltung by F. Handel THE MAIN EVENT! These are the men Sie sind die Besten "Champions League" by Tony Britten THESE ARE THE CHAMPIONS! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.32.81.146

11/26 21:46, , 1F
謝謝~我是要應用在嵌入式系統的,我會在修看看的^^
11/26 21:46, 1F

11/27 21:02, , 2F
那個...c語言的int是要看CPU多少bit就是多少bit吧?
11/27 21:02, 2F

11/27 23:55, , 3F
印象中int通常就是4byte,long才有差別,印象中XD
11/27 23:55, 3F

11/28 00:17, , 4F
K&R: int an integer, typically reflecting the natural
11/28 00:17, 4F

11/28 00:19, , 5F
size of integers on the host machine (CPU<=我加的)
11/28 00:19, 5F

11/28 00:20, , 6F
差不多是說CPU的adder可以用到的大小,32bit cpu -> 4byte
11/28 00:20, 6F

11/28 00:24, , 7F
但是像int有下限: INT_MAX 32767
11/28 00:24, 7F

11/28 00:25, , 8F
16byte
11/28 00:25, 8F

11/28 00:25, , 9F
16bit... 2byte
11/28 00:25, 9F

11/30 20:39, , 10F
樓上的定義我個人覺得用在pointer上比較合理
11/30 20:39, 10F

11/30 20:40, , 11F
不過這種平台相依的東西就case by case了
11/30 20:40, 11F
文章代碼(AID): #1Gislyry (Python)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
文章代碼(AID): #1Gislyry (Python)