Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Binary conversion

Status
Not open for further replies.

selimsl

Programmer
Aug 15, 2005
62
0
0
TR
Hi!

Code:
char ascii[13];
short int datax;
datax=10;
sprintf(ascii,"%6d",datax);

result is: ascii-> " 10"

Is there any way to convert int data to binary array.I mean,

Code:
short int datax;
datax=10;
function(ascii,datax);

result is: ascii->"0000000000001010"

Thanks in advice
 
No standard library function to form a binary text representation of int/short. But it's a very (very!) simple task to write your own function for this...
 
If you were using C++ you could do it like this:
Code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

template <class T>
std::string ToBinaryString( T  num )
{
	char c;
	const int size = (sizeof( T ) * 8);
	unsigned int mask = (1 << (size - 1));
	std::stringstream str;

	for ( int i = 0; i < size; ++i )
	{
		if ( (num & mask) == mask )
		{
			c = '1';
		}
		else
		{
			c = '0';
		}

		str << c;
		mask = (mask >> 1);
	}

	return str.str();
}

int main()
{
	char           c  = (char)0xAA;
	short          s  = (short)0xAAAA;
	int            i  = 0xAAAAAAAA;
	unsigned char  uc = 0xAA;
	unsigned short us = 0xAAAA;
	unsigned int   ui = 0xAAAAAAAA;

	cout << ToBinaryString( c ) << endl
	     << ToBinaryString( s ) << endl
	     << ToBinaryString( i ) << endl
	     << ToBinaryString( uc ) << endl
	     << ToBinaryString( us ) << endl
	     << ToBinaryString( ui ) << endl;

	return 0;
}
But with C you'd need to make a sprintf() type of function and code the logic for each of the %c, %d, %u specifiers...
 
I know the question was concerning C, but...

cpjust, a slightly shorter way to write that in C++ would be:
Code:
template <class T>
std::string ToBinaryString( T  num )
{
    std::bitset<sizeof(T) * 8> bits(num);
    return bits.to_string();
}

template <unsigned long NBits, class T>
std::string ToBinaryStringNBits( T  num )
{
    std::bitset<NBits> bits(num);
    return bits.to_string();
}

int main ()
{
    std::cout << ToBinaryString(7) << '\n';
    std::cout << ToBinaryStringNBits<4>(7) << '\n';
}

// Output:
//
// 00000000000000000000000000000111
// 0111
 
Well I'll be damned...
I haven't used bitset much, so I didn't even know you could do that, thanks!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top