[英]How to store the bit pattern of a 32 bit integer in a 32 length string of 0s and 1s in C
[英]How do I convert and store a 32 bit int value into a 32 length string of its binary pattern?
我將 function 設置為: int int2bitstr(int I, char *str) {}
我正在嘗試采用 int I 並使用循環和位級操作將該 32 位 int 轉換為包含其二進制模式 0 和 1 的 32 長度字符串 str。 排序是從最高有效位到最低位。 它需要適用於有符號和無符號整數。 最后,我不能使用 function 調用,除 (++) 和 (--) 以外的算術運算,也不能使用 switch 語句。 老實說,我不知道從哪里開始,也無法在網上找到任何東西,所以任何幫助解釋我需要 go 的過程都會很棒。
#include <stdio.h>
#include <stdint.h>
#include <limits.h>
int int2bitstr(int I, char *str)
{
for(int n=32; n>0; *str++ = "01"[!!(1<<--n&I)]);
return *str = '\0';
}
int main(void) {
char str[33]; // Enough space for 32-bits + Terminator
int2bitstr(13421, str);
printf("Answer: %s\n", str);
return 0;
}
Success #stdin #stdout 0s 5436KB
Answer: 00000000000000000011010001101101
=
)>
)*
)++
和--
)"
)[ ]
)!
)<<
)&
)我認為就是這樣,而且我認為您的要求中沒有禁止任何內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.