【问题标题】:Unsigned short int to Binary in C without using malloc() function?在不使用 malloc() 函数的情况下,在 C 中将无符号 short int 转换为二进制?
【发布时间】:2022-01-01 05:43:33
【问题描述】:

我编写了一个程序,将 unsigned int 转换为二进制。在我的函数中,我使用 malloc() 函数。我想知道是否有办法在没有 malloc() 的情况下做到这一点。

#include <stdio.h>
#include <stdlib.h>

char *toBinary(unsigned n);

int main(void) {
     int n;

     printf("Enter an integer to convert: ");
     scanf("%d",&n);

     char* binary = toBinary(n); 

     printf("%s",binary);

     return 0;
} 


char* toBinary(unsigned n) {
     char* binary = (char*)malloc(sizeof(char) * 16);
     int j = 0;
     unsigned i;
     for (i = 1 << 16; i > 0; i = i / 2) {
             if(j == 8)
                   binary[j++] = ' ';
             else
                   binary[j++] = (n & i) ? '1' : '0'; 
     }
    binary[j]='\0';
    return binary;
}
~                      

【问题讨论】:

  • 是的,有一种方法,在main 中声明binary 数组,例如:char binary[33](33,因为您可能需要 32 字节 + 加上一个空终止符),然后传递 binary作为toBinary 的第二个参数。
  • 代码中没有提到short,尽管硬编码的16 可能是对sizeof(short) 的引用。有趣的是,sizeof(char)1 相同,并且毫无意义——因此您既过度使用又未充分使用sizeof 运算符。此外,您没有分配足够的空间;您需要在内存分配中添加一个字节以允许空字节 - 或您在输出中添加的空间。
  • 旁注:如果您已经使用i = 1 &lt;&lt; 16 进行初始化,我真的更喜欢在后循环操作中使用i &gt;&gt;= 1,尽管两者是等价的。
  • 哦,你malloc'ed 数组太短了两个,因为你在中间添加一个空格并以空值结尾字符串!

标签: c type-conversion bit unsigned-integer


【解决方案1】:

很简单:将预分配的缓冲区传递给函数:

typedef enum
{
    CE_NoError,
    CE_InsufficientMemory,
} ConversionError;

ConversionError toBinary(unsigned int n, size_t length, char binary[length])
{
   // check first if length suffices to hold all characters
   // plus the terminating null character

   // use the array passed to instead of the one malloc'ed one...
}

用法:

char binary[sizeof(unsigned int) * CHAR_BIT + /*1*/ 2]; // (!): intermediate space!
if(toBinary(theValue, sizeof(binary), binary) != CE_NoError)
{
    // appropriate error handling!
}

如果您认为枚举仅适用于一种错误类型,则可能会返回 bool(需要包含 stdbool.h)而不是枚举...

旁注:如果您确实想按照标题(以及您的 for 循环指示)转换 unsigned short,请将 unsigned int(来自您的代码)替换为 unsigned short

【讨论】:

  • unsigned short -> unsigned intunsigned n 等价于 unsigned int n
  • 在现代风格中,您最好使用int toBinary(unsigned n, size_t length, char binary[length]) { … },其中关键更改在参数列表中(先指定大小,然后在数组声明中使用它),次要更改是返回int状态,这样如果缓冲区太小,可以报错。传统上,如果一切正常,则返回 0,失败时返回一些其他值(可能为负值)。
  • @JonathanLeffler 对于程序的退出状态,“0 是好的”经验法则实际上比 C 中函数的返回值更正确。
  • @Peter-ReinstateMonica — 这确实取决于你在哪里看。没有其他信息可返回的 Unix 系统调用在成功时返回 0,在失败时返回 -1。 POSIX Pthreads 在成功时返回 0,在失败时返回(正)错误号。我使用的软件大多使用 0 表示成功,(大部分)使用负数表示失败。有反例:IIRC,OpenSSL 在失败时返回 0。您付钱并选择。我更喜欢零成功变体。
  • @JonathanLeffler 没错——许多函数都会返回一些东西。程序可以“返回”结果作为输出(grep 等),此外还提供诊断退出代码;函数通常不是为此而设计的(尽管 `bool tryXY(some_arg, some result_ref) 的范例似乎变得更加普遍,尤其是对于 C# 和 Java,因为它保存了一个分配/释放对。但是“OK”是 1 ; -) ) bool 返回(或等效)通常会导致优雅的风格,例如 (while(cin >> i))。
猜你喜欢
  • 2015-04-29
  • 2014-05-26
  • 2013-07-02
  • 1970-01-01
  • 2014-06-26
  • 2014-05-19
  • 2019-03-22
  • 1970-01-01
  • 2019-03-18
相关资源
最近更新 更多