打印使用C二进制重新presentation一个int [英] Print an int in binary representation using C

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

问题描述

我正在寻找一个功能,让我打印一个int的二进制重新presentation。我有什么到目前为止;

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;

}

但是,当我打电话

But when I call

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

我得到的输出等;

I get output like;

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的code是这里

编辑:这不是功课通知你,我要调试别人的图像处理例程在一个陌生的语言。然而,如果它被标记为功课,因为它是一个基本的概念,然后公平竞争。

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] = '\0';

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

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

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

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