作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要在 C 中将整数转换为位字符串。我已经编写了一个函数来实现此目的(示例)并且需要知道更好的解决方案。
例如:
char* int_to_bin(int n)
{
char arr[] = "00000000000000000000000000000000"; // 32 zeros , coz int => 32 bit
int pos = 0;
while(n!=0)
{
char element = (n%2==0)?'0':'1';
arr[pos] = element;
n /= 2;
pos++;
}
char *str = malloc(sizeof(char)*(pos+1)); // need to malloc for future use
for(int i = 0; i<pos; i++) // get the reverse
{
*(str+i) = arr[pos-1-i];
}
*(str+pos) = '\0';
return str;
}
最佳答案
您可以避免内存复制并让编译器通过使用固定次数的迭代来展开循环:
char* int_to_bin(unsigned n) {
unsigned size = sizeof(n) * CHAR_BIT;
char* str = malloc(size + 1);
str[size] = 0;
while(size--) {
str[size] = '0' + (n & 1);
n >>= 1;
}
return str;
}
关于c - 在 C 中将整数转换为位串的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57498965/
我正在尝试创建一个程序,其中字符串的前三个字符重复给定次数,如下所示: foo('Chocolate', 3) # => 'ChoChoCho' foo('Abc', 3) # => 'AbcAbcA
我有以下字符串: std::string str = "Mode:AAA:val:101:id:A1"; 我想分离一个位于 "val:" 和 ":id" 之间的子字符串,这是我的方法: std::st
DNA 字符串可以是任意长度,包含 5 个字母(A、T、G、C、N)的任意组合。 压缩包含 5 个字母(A、T、G、C、N)的 DNA 字母串的有效方法是什么?不是考虑每个字母表 3 位,我们可以使用
是否有一种使用 levenstein 距离将一个特定字符串与第二个较长字符串中的任何区域进行匹配的好方法? 例子: str1='aaaaa' str2='bbbbbbaabaabbbb' if str
使用 OAuth 并使用以下函数使用我们称为“foo”(实际上是 OAuth token )的字符串加密 key public function encrypt( $text ) { // a
我是一名优秀的程序员,十分优秀!