我正在寻找一个允许我打印int的二进制表示的函数。到目前为止我所拥有的是什么;
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(以及一堆未知字符。
这是函数中的缺陷还是打印字符数组的地址?对不起,我只是看不出我出错的地方。
注意:代码来自here
编辑:这不是家庭作业FYI,我正在尝试用不熟悉的语言调试其他人的图像处理程序。然而,如果它被标记为家庭作业,因为它是一个基本概念,然后公平竞争。答案 0 :(得分:30)
这是另一个在传递分配的缓冲区时更加优化的选项。确保它的大小正确。
// 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);
}
答案 1 :(得分:8)
一些建议:
malloc()
malloc()
以下是代码:
#include <stdlib.h>
#include <limits.h>
char * int2bin(int i)
{
size_t bits = sizeof(int) * CHAR_BIT;
char * str = malloc(bits + 1);
if(!str) return NULL;
str[bits] = 0;
// type punning because signed shift is implementation-defined
unsigned u = *(unsigned *)&i;
for(; bits--; u >>= 1)
str[bits] = u & 1 ? '1' : '0';
return str;
}
答案 2 :(得分:7)
您的字符串不是以空值终止的。确保在字符串的末尾添加'\0'
字符;或者,您可以使用calloc
而不是malloc
来分配它,这会将返回给您的内存归零。
顺便说一下,这段代码还有其他问题:
free()
分配的字符串。如果你只是在printf
电话中打电话,你就会泄漏内存。这是您可以使用的替代实现。
#include <stdlib.h>
#include <limits.h>
char *int2bin(unsigned n, char *buf)
{
#define BITS (sizeof(n) * CHAR_BIT)
static char static_buf[BITS + 1];
int i;
if (buf == NULL)
buf = static_buf;
for (i = BITS - 1; i >= 0; --i) {
buf[i] = (n & 1) ? '1' : '0';
n >>= 1;
}
buf[BITS] = '\0';
return buf;
#undef BITS
}
用法:
printf("%s\n", int2bin(0xFF00000000, NULL));
第二个参数是指向要存储结果字符串的缓冲区的指针。如果没有缓冲区,则可以传递NULL
,int2bin
将写入{{1缓冲区并将其返回给您。这比原始实现的优点是调用者不必担心static
返回的字符串。
缺点是只有一个静态缓冲区,因此后续调用将覆盖先前调用的结果。您无法保存多个调用的结果以供以后使用。此外,它不是线程安全的,这意味着如果你从不同的线程以这种方式调用函数,它们可能会破坏彼此的字符串。如果有可能你需要传递自己的缓冲区而不是传递free()
,如下:
NULL
答案 3 :(得分:1)
这是一个简单的算法。
void decimalToBinary (int num) {
//Initialize mask
unsigned int mask = 0x80000000;
size_t bits = sizeof(num) * CHAR_BIT;
for (int count = 0 ;count < bits; count++) {
//print
(mask & num ) ? cout <<"1" : cout <<"0";
//shift one to the right
mask = mask >> 1;
}
}
答案 4 :(得分:1)
这就是我将整数显示为binairy代码所做的,每4位分隔一次:
int getal = 32; /** To determain the value of a bit 2^i , intergers are 32bits long**/
int binairy[getal]; /** A interger array to put the bits in **/
int i; /** Used in the for loop **/
for(i = 0; i < 32; i++)
{
binairy[i] = (integer >> (getal - i) - 1) & 1;
}
int a , counter = 0;
for(a = 0;a<32;a++)
{
if (counter == 4)
{
counter = 0;
printf(" ");
}
printf("%i", binairy[a]);
teller++;
}
它可能有点大,但我总是以某种方式(我希望)写出来,每个人都能理解发生了什么。希望这会有所帮助。
答案 5 :(得分:1)
#include<stdio.h>
//#include<conio.h> // use this if you are running your code in visual c++, linux don't
// have this library. i have used it for getch() to hold the screen for input char.
void showbits(int);
int main()
{
int no;
printf("\nEnter number to convert in binary\n");
scanf("%d",&no);
showbits(no);
// getch(); // used to hold screen...
// keep code as it is if using gcc. if using windows uncomment #include & getch()
return 0;
}
void showbits(int n)
{
int i,k,andmask;
for(i=15;i>=0;i--)
{
andmask = 1 << i;
k = n & andmask;
k == 0 ? printf("0") : printf("1");
}
}
答案 6 :(得分:0)
#include <stdio.h>
int main(void) {
int a,i,k=1;
int arr[32]; \\ taken an array of size 32
for(i=0;i <32;i++)
{
arr[i] = 0; \\initialised array elements to zero
}
printf("enter a number\n");
scanf("%d",&a); \\get input from the user
for(i = 0;i < 32 ;i++)
{
if(a&k) \\bit wise and operation
{
arr[i]=1;
}
else
{
arr[i]=0;
}
k = k<<1; \\left shift by one place evry time
}
for(i = 31 ;i >= 0;i--)
{
printf("%d",arr[i]); \\print the array in reverse
}
return 0;
}
答案 7 :(得分:0)
这是我的解决方案。它创建一个掩码,从所有0开始,最左边的位为1,并在假定的 32位整数中为每个位逻辑移位。通过将当前屏蔽的整数的值转换为布尔值来顺序打印这些位。
void printBits(int val){
for(unsigned int mask = 0x80000000; mask; mask >>= 1){
printf("%d", !!(mask & val));
}
}
答案 8 :(得分:0)
不是那么优雅,但实现了你的目标,而且很容易理解:
#include<stdio.h>
int binario(int x, int bits)
{
int matriz[bits];
int resto=0,i=0;
float rest =0.0 ;
for(int i=0;i<8;i++)
{
resto = x/2;
rest = x%2;
x = resto;
if (rest>0)
{
matriz[i]=1;
}
else matriz[i]=0;
}
for(int j=bits-1;j>=0;j--)
{
printf("%d",matriz[j]);
}
printf("\n");
}
int main()
{
int num,bits;
bits = 8;
for (int i = 0; i < 256; i++)
{
num = binario(i,bits);
}
return 0;
}
答案 9 :(得分:0)
#include <stdio.h>
#define BITS_SIZE 8
void
int2Bin ( int a )
{
int i = BITS_SIZE - 1;
/*
* Tests each bit and prints; starts with
* the MSB
*/
for ( i; i >= 0; i-- )
{
( a & 1 << i ) ? printf ( "1" ) : printf ( "0" );
}
return;
}
int
main ()
{
int d = 5;
printf ( "Decinal: %d\n", d );
printf ( "Binary: " );
int2Bin ( d );
printf ( "\n" );
return 0;
}
答案 10 :(得分:0)
这是另一个不需要char *的解决方案。
public class TestSetup {
private String browserFlavor;
private static final ThreadLocal<RemoteWebDriver> driver = new ThreadLocal<RemoteWebDriver>() {
@Override
protected RemoteWebDriver initialValue() {
//By default lets set the browser flavor always as Chrome.
return new ChromeDriver();
}
};
@Parameters ({"browserParam"})
@BeforeClass (alwaysRun = true)
public void beforeClass(@Optional ("") final String browserParam) {
this.browserFlavor = browserParam;
}
@BeforeMethod
public void instantiateBrowser() {
switch (browserFlavor) {
case "firefox":
driver.set(new FirefoxDriver());
break;
case "ie":
driver.set(new InternetExplorerDriver());
break;
}
}
@Test
public void testMethod() {
driver.get().get("http://www.google.com");
}
}
或者这里是为了更加可读:
#include <stdio.h>
#include <stdlib.h>
void print_int(int i)
{
int j = -1;
while (++j < 32)
putchar(i & (1 << j) ? '1' : '0');
putchar('\n');
}
int main(void)
{
int i = -1;
while (i < 6)
print_int(i++);
return (0);
}
这是输出:
#define GRN "\x1B[32;1m"
#define NRM "\x1B[0m"
void print_int(int i)
{
int j = -1;
while (++j < 32)
{
if (i & (1 << j))
printf(GRN "1");
else
printf(NRM "0");
}
putchar('\n');
}
答案 11 :(得分:0)
我这样做的最简单方法(8位表示):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
char *intToBinary(int z, int bit_length){
int div;
int counter = 0;
int counter_length = (int)pow(2, bit_length);
char *bin_str = calloc(bit_length, sizeof(char));
for (int i=counter_length; i > 1; i=i/2, counter++) {
div = z % i;
div = div / (i / 2);
sprintf(&bin_str[counter], "%i", div);
}
return bin_str;
}
int main(int argc, const char * argv[]) {
for (int i = 0; i < 256; i++) {
printf("%s\n", intToBinary(i, 8)); //8bit but you could do 16 bit as well
}
return 0;
}
答案 12 :(得分:0)
//当我们的老师要求我们这样做时,这就是我所做的
int main (int argc, char *argv[]) {
int number, i, size, mask; // our input,the counter,sizeofint,out mask
size = sizeof(int);
mask = 1<<(size*8-1);
printf("Enter integer: ");
scanf("%d", &number);
printf("Integer is :\t%d 0x%X\n", number, number);
printf("Bin format :\t");
for(i=0 ; i<size*8 ;++i ) {
if ((i % 4 == 0) && (i != 0)) {
printf(" ");
}
printf("%u",number&mask ? 1 : 0);
number = number<<1;
}
printf("\n");
return (0);
}
答案 13 :(得分:0)
编码here的两个简单版本(通过温和的重新格式化再现)。
#include <stdio.h>
/* Print n as a binary number */
void printbitssimple(int n)
{
unsigned int i;
i = 1<<(sizeof(n) * 8 - 1);
while (i > 0)
{
if (n & i)
printf("1");
else
printf("0");
i >>= 1;
}
}
/* Print n as a binary number */
void printbits(int n)
{
unsigned int i, step;
if (0 == n) /* For simplicity's sake, I treat 0 as a special case*/
{
printf("0000");
return;
}
i = 1<<(sizeof(n) * 8 - 1);
step = -1; /* Only print the relevant digits */
step >>= 4; /* In groups of 4 */
while (step >= n)
{
i >>= 4;
step >>= 4;
}
/* At this point, i is the smallest power of two larger or equal to n */
while (i > 0)
{
if (n & i)
printf("1");
else
printf("0");
i >>= 1;
}
}
int main(int argc, char *argv[])
{
int i;
for (i = 0; i < 32; ++i)
{
printf("%d = ", i);
//printbitssimple(i);
printbits(i);
printf("\n");
}
return 0;
}
答案 14 :(得分:0)
两件事:
'\0'
的地方。while (a > 0)
会立即失效。旁白:里面的malloc函数很难看。如何为int2bin提供缓冲区?
答案 15 :(得分:0)
有几件事:
int f = 32;
int i = 1;
do{
str[--f] = i^a?'1':'0';
}while(i<<1);
答案 16 :(得分:-1)
void print_binary(int n) {
if (n == 0 || n ==1)
cout << n;
else {
print_binary(n >> 1);
cout << (n & 0x1);
}
}