看板 C_and_CPP 關於我們 聯絡資訊
※ 引述《IOP14759 (iop14759)》之銘言: : 開發平台(Platform): (Ex: Win10, Linux, ...) : WIN8 : 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) : c++builder : 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) : 無 : 問題(Question): : 想請教此程式如果想寫成迴圈該怎麼寫? : 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) : int pcs,ID,count; : AnsiString bit0,bit1,bit2,bit3,bit4,bit5,bit6,bit7,ID_display; : //將ID轉為2進制的字串 : bit1=(ID&0x02)>>1; : bit2=(ID&0x04)>>2; : bit3=(ID&0x08)>>3; : bit4=(ID&0x10)>>4; : bit5=(ID&0x20)>>5; : bit6=(ID&0x40)>>6; : bit7=(ID&0x80)>>7; : ////////////////////////////////////////////////////////////////// : if(pcs==1)ID_display=bit7; : if(pcs==2)ID_display=bit7+bit6; : if(pcs==3)ID_display=bit7+bit6+bit5; : if(pcs==4)ID_display=bit7+bit6+bit5+bit4; : if(pcs==5)ID_display=bit7+bit6+bit5+bit4+bit3; : if(pcs==6)ID_display=bit7+bit6+bit5+bit4+bit3+bit2; : if(pcs==7)ID_display=bit7+bit6+bit5+bit4+bit3+bit2+bit1; //最多7個 這段程式看來僅將一個整數取出由右數來第八到第二位元的資料, pcs 由第八個位元起往右取 pcs 個位元存到 ID_display 字串上。 程式問題還滿簡單的,以下用一個陣列將不同的 pcs 的結果存起來。 // id = 10110101 int id = 0xb5 ; string s ; int i , j , p = 7 ; vector<string> id_display(p) ; for ( i = 0 ; i < p ; ++i ) { s = "" ; for ( j = p ; j > p-1-i ; --j ) { s += ( ( id >> j )%2 ? "1" : "0" ) ; } id_display[i] = s ; } cout << "> ID : " << showbase << hex << id << endl ; cout << noshowbase ; for ( i = 0 ; i < id_display.size() ; ++i ) { cout << i << ":" << id_display[i] << endl ; } 輸出: > ID : 0xb5 0:1 1:10 2:101 3:1011 4:10110 5:101101 6:1011010 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.115.25.29 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1586573080.A.1D3.html