用C语言将二进制格式字符串转换为int
如何将二进制字符串(如“010011101”)转换为int,以及如何将int(如5)转换为C中的字符串“101”?标准库中的用C语言将二进制格式字符串转换为int,c,C,如何将二进制字符串(如“010011101”)转换为int,以及如何将int(如5)转换为C中的字符串“101”?标准库中的strtol函数采用“base”参数,在本例中为2 int fromBinary(const char *s) { return (int) strtol(s, NULL, 2); } (我写了大约8年的第一个C代码:-)我想这真的取决于关于字符串/程序的一些问题。例如,如果您知道您的数字不会大于255(即您仅使用8位或8 0s/1),则可以创建一个函数,在该函数中,
strtol
函数采用“base”参数,在本例中为2
int fromBinary(const char *s) {
return (int) strtol(s, NULL, 2);
}
(我写了大约8年的第一个C代码:-)我想这真的取决于关于字符串/程序的一些问题。例如,如果您知道您的数字不会大于255(即您仅使用8位或8 0s/1),则可以创建一个函数,在该函数中,您从字符串中输入8位,遍历它并将其添加到每次碰到1时返回的总和中。也就是说,如果你击中2^7的位,加128,下一个击中的位是2^4加16
这是我的又快又脏的主意。我想你在学校的时候可以多用谷歌搜索一下D如果这是一个家庭作业问题,他们可能希望您实现
strtol
,您将有一个类似以下内容的循环:
char* start = &binaryCharArray[0];
int total = 0;
while (*start)
{
total *= 2;
if (*start++ == '1') total += 1;
}
char c[20];
int s=23;
itoa(s,c,2);
puts(c);
如果你想变得更花哨,你可以在循环中使用这些:
total <<= 1;
if (*start++ == '1') total^=1;
total对于问题的第二部分,即“如何将int(如5)转换为C中的字符串“101?”,请尝试以下操作:
void
ltostr( unsigned long x, char * s, size_t n )
{
assert( s );
assert( n > 0 );
memset( s, 0, n );
int pos = n - 2;
while( x && (pos >= 0) )
{
s[ pos-- ] = (x & 0x1) ? '1' : '0'; // Check LSb of x
x >>= 1;
}
}
您可以使用以下编码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
int nRC = 0;
int nCurVal = 1;
int sum = 0;
char inputArray[9];
memset(inputArray,0,9);
scanf("%s", inputArray);
// now walk the array:
int nPos = strlen(inputArray)-1;
while(nPos >= 0)
{
if( inputArray[nPos] == '1')
{
sum += nCurVal;
}
--nPos;
nCurVal *= 2;
}
printf( "%s converted to decimal is %d\n", inputArray, sum);
return nRC;
}
#包括
#包括
#包括
内部主(空)
{
int nRC=0;
int nCurVal=1;
整数和=0;
字符输入阵列[9];
memset(输入阵列,0,9);
scanf(“%s”,输入阵列);
//现在浏览阵列:
int nPos=strlen(输入阵列)-1;
而(非营利组织>=0)
{
if(输入阵列[nPos]=“1”)
{
sum+=nCurVal;
}
--非营利组织;
nCurVal*=2;
}
printf(“%s转换为十进制为%d\n”,输入数组,总和);
返回nRC;
}
像这样使用:
char* start = &binaryCharArray[0];
int total = 0;
while (*start)
{
total *= 2;
if (*start++ == '1') total += 1;
}
char c[20];
int s=23;
itoa(s,c,2);
puts(c);
输出:
10111
回答问题的第二部分
char* get_binary_string(uint16_t data, unsigned char sixteen_bit)
{
char* ret = NULL;
if(sixteen_bit) ret = (char*)malloc(sizeof(char) * 17);
else ret = (char*)malloc(sizeof(char) * 9);
if(ret == NULL) return NULL;
if(sixteen_bit){
for(int8_t i = 15; i >= 0; i--){
*(ret + i) = (char)((data & 1) + '0');
data >>= 1;
}
*(ret + 16) = '\0';
return ret;
}else{
for(int8_t i = 7; i >= 0; i--){
*(ret + i) = (char)((data & 1) + '0');
data >>= 1;
}
*(ret + 8) = '\0';
return ret;
}
return ret;
}
问题的前半部分在C语言中,没有内置的“null”文本。有一个宏,NULL,所以它需要大写。此外,字符串参数应设为“const”,因为函数不会修改它。哦,对了。我,在编译器告诉我错误后,我可能会使用“0:-)找到更奇特的解决方案。`while(len-){ret=(ret我认为您需要从结束
开始,从右到左工作。注意:itoa
是一个非标准C函数