作者chuanmaotou (魯蛇)
看板C_and_CPP
標題[問題] 讀取十六進位制字串再轉成integer
時間Wed Jun 17 10:42:59 2015
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
C++
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
STL
問題(Question):
從一個二進位制的檔案讀入資料將他轉換成64bit-signed int
內容大概像這樣
char s[
9]={
'\x00',
'\x00',
'\x00',
'\x6a',
'\x46',
'\xd2',
'\xdf',
'\x44'};
原本我是自己寫一個函式用位元運算硬轉 但因為是signed integer還有負數
處裡很複雜 所以放棄自己寫一個函式來轉
有翻過cpp reference 似乎可以用stringstream來轉換
但試驗後 似乎必須是*s=
"0x0000006a46d2df44"這類的形式才能直接用stringstream轉
有想過把'\xff'形式的字元轉成"FF"後餵給stringstream
但似乎又有點多此一舉 不知道是不是有什麼更好的方法可以轉換?
餵入的資料(Input):
char s[
9]={
'\x00',
'\x00',
'\x00',
'\x6a',
'\x46',
'\xd2',
'\xdf',
'\x44'};
(一個從檔案讀入的hex字串 00 00 00 6A 46 D2 DF 44 )
預期的正確結果(Expected Output):
456454758212
錯誤結果(Wrong Output):
程式碼(Code):(請善用置底文網頁, 記得排版)
補充說明(Supplement):
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.26.95.65
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1434508982.A.86F.html
→ Feis: int64_t, 然後可能有 order 的問題 06/17 10:54
→ chuanmaotou: 剛剛試了一下reinterpret_cast 答案似乎不正確 06/17 11:04
→ chuanmaotou: 不知道是不是因為資料是big endian所致? 06/17 11:04
→ chuanmaotou: 剛剛我把uint64_t改成int64_t 06/17 11:47
→ chuanmaotou: (因為輸入是signed integer) 06/17 11:48
→ chuanmaotou: 結果好像遇到negative integer會有問題 06/17 11:49
→ chuanmaotou: 比方FF FF FF 96 BA 2E 21 BC 06/17 11:49
→ chuanmaotou: 出來是FF FF FF 97 BB 2F 22 BC 06/17 11:50
→ chuanmaotou: 會不會是因為1's和2's complement的差異所造成? 06/17 11:51
→ anyoiuo: 假如你hex檔是存二進制(ex. 44 DF D2 46 6A 00 00 00...) 06/17 15:23
→ anyoiuo: 這樣可以直接fread(i64Array, sizeof(int64_t), count) 06/17 15:23
→ anyoiuo: fread(i64Array, sizeof(int64_t), i64Count, fin); 06/17 15:24