c - 删除 c 中的前导零

标签 c function gcc zero

我想将十进制转换为二进制,但输出应该没有前导零,那么如何删除零呢? (代码有效,是用 C 编写的)

int* dec2bin(int, int[]);

main(){
  int var=0;
  int n[16];
  printf("Number(>=0, <65535): ");
  scanf("%d", &var);
  dec2bin(var, n);
  printf(" %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n", n[0], n[1],n[2],n[3],n[4],n[5],n[6],n[7],n[8],n[9],n[10],n[11],n[12],n[13],n[14],n[15]);
}

int* dec2bin(int N, int n[]){
  int count = 15;
  for(count=15; count >=0; count--){
    n[count] = N%2;
    N=N/2;
  }
}

最佳答案

// Skip leading zeros
int d = 0 ;
for( d = 0; n[d] == 0 && d < 15; d++ )
{
    // nothing
}   

// Print significant digits
for( ; d < 16; d++ )
{
    printf( "%d ", n[d] ) ;
}    

请注意,dec2bin 生成一个 int 形式的二进制数字数组。这显然不是从十进制到二进制的转换,因为int已经是二进制了 - scanf()调用已经完成了到二进制的转换(int) 与 %d 说明符。由于该函数已经是二进制的,因此过于复杂。您实际上所做的只是将单个位扩展为整数值 0 和 1 的数组。

考虑:

int* int2bin( int N, int n[] )
{
  for( int d = 15; d >= 0; d-- )
  {
    n[d] = (N & (0x0001 << d)) == 0 ? 0 : 1 ;
  }

  return n ;
}

然而,生成一个 ASCII 数字字符串而不是一个整数数组可能更有意义。

char* int2bin( int val, char* str )
{
    // Skip leading zeros
    int d = 0 ;
    for( d = 0; (val & (1<<d)) == 0 && d < 15; d++ )
    {
        // nothing
    }   

    // Significant digits
    for( int s = 0 ; d < 16; s++; d++ )
    {
        str[s] = (val & (1<<d)) == 0 ? '0' : '1' ;
    }    

    str[s] = 0 ;

    return str ;
}

那么输出很简单:

  char n[17] ;
  printf("%s", int2bin(var, n) ) ;

关于c - 删除 c 中的前导零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47444431/

相关文章:

python - 使用 ctypes 从 C 结构数组到 NumPy 数组的高效转换

c++ - directx 9 与 Visual Studio 2012 Express

ios - 无法为 arm (iOS) 交叉编译 C 库

c++ - C 执行期间记录错误

c - 如何使用原始名称为库函数创建包装器?

c - IPC消息队列。 msgrcv 系统调用。系统五、如何跳出循环

c - C 中的 double 计算器

javascript - forEach 中箭头函数内的三元运算符

C 函数调用 : Understanding the "implicit int" rule

javascript - 当变量等于函数时,这意味着什么?