使用 C 以二进制表示形式打印 int [英] Print an int in binary representation using C

查看:33
本文介绍了使用 C 以二进制表示形式打印 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个函数来允许我打印 int 的二进制表示.到目前为止我所拥有的是;

I'm looking for a function to allow me to print the binary representation of an int. What I have so far is;

char *int2bin(int a)
{
 char *str,*tmp;
 int cnt = 31;
 str = (char *) malloc(33); /*32 + 1 , because its a 32 bit bin number*/
 tmp = str;
 while ( cnt > -1 ){
      str[cnt]= '0';
      cnt --;
 }
 cnt = 31;
 while (a > 0){
       if (a%2==1){
           str[cnt] = '1';
        }
      cnt--;
        a = a/2 ;
 }
 return tmp;

}

但是当我打电话时

printf("a %s",int2bin(aMask)) // aMask = 0xFF000000

我得到像这样的输出;

0000000000000000000000000000000000xtpYy(还有一堆未知字符.

0000000000000000000000000000000000xtpYy (And a bunch of unknown characters.

这是函数中的缺陷还是我打印了字符数组的地址或其他什么?抱歉,我只是看不出哪里出错了.

Is it a flaw in the function or am I printing the address of the character array or something? Sorry, I just can't see where I'm going wrong.

NB 代码来自这里

这不是家庭作业仅供参考,我正在尝试用不熟悉的语言调试其他人的图像处理例程.但是,如果它被标记为作业,因为它是一个基本概念,那么公平竞争.

It's not homework FYI, I'm trying to debug someone else's image manipulation routines in an unfamiliar language. If however it's been tagged as homework because it's an elementary concept then fair play.

推荐答案

这是另一个更优化的选项,您可以传入分配的缓冲区.确保它的大小正确.

Here's another option that is more optimized where you pass in your allocated buffer. Make sure it's the correct size.

// buffer must have length >= sizeof(int) + 1
// Write to the buffer backwards so that the binary representation
// is in the correct order i.e.  the LSB is on the far right
// instead of the far left of the printed string
char *int2bin(int a, char *buffer, int buf_size) {
    buffer += (buf_size - 1);

    for (int i = 31; i >= 0; i--) {
        *buffer-- = (a & 1) + '0';

        a >>= 1;
    }

    return buffer;
}

#define BUF_SIZE 33

int main() {
    char buffer[BUF_SIZE];
    buffer[BUF_SIZE - 1] = '';

    int2bin(0xFF000000, buffer, BUF_SIZE - 1);

    printf("a = %s", buffer);
}

这篇关于使用 C 以二进制表示形式打印 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆