[Qt-interest] QBitArray convertion

Nathan Carter nathancarter5 at gmail.com
Wed May 27 20:42:01 CEST 2009


You mean that if you had the integer 53, you would want a bit array  
like [true,true,false,true,false,true]?  Are you hoping for something  
that works for a specific number of bits, like qint16, always  
returning a bit array of length 16, or are you hoping for something  
that will detect the number of bits in the representation of an  
integer on the platform you're on?

You can detect the number of bits in an integer with  
sizeof(int)*CHAR_BIT, where CHAR_BIT is defined in climits, as per  
this doc: http://www.cppreference.com/wiki/keywords/sizeof

But here's a solution that doesn't rely on that.  (untested)

QBitArray intToBitArray ( int theInputInteger )
{
	// this whole solution assumes least significant bit on right;
	// extending to handle other case left as exercise to reader
	static int numBitsInAnInt = -1;
	if ( numBitsInAnInt == -1 ) {
		int myMovingBit = 1;
		while ( myMovingBit ) {
			numBitsInAnInt++;
			myMovingBit = myMovingBit << 1;
		}
	}
	// now numBits is how many bits there are in an integer
	// but you could eliminate the above loop with the  
sizeof(int)*CHAR_BIT thing
	QBitArray result( numBitsInAnInt );
	for ( int i = 0 ; i < numBitsInAnInt ; i++ )
		results[numBitsInAnInt-1-i] = theInputInteger & ( 1 << i );
	return result;
}

Nathan


On May 27, 2009, at 2:07 PM, Parker wrote:

> Hi all,
> does anyone knows how to convert and integer to QBitArray and vice  
> versa ?
> I can't actually find a way... :/
>
>
> __________ Information from ESET NOD32 Antivirus, version of virus  
> signature database 4098 (20090522) __________
>
> The message was checked by ESET NOD32 Antivirus.
>
> http://www.eset.com
> _______________________________________________
> Qt-interest mailing list
> Qt-interest at trolltech.com
> http://lists.trolltech.com/mailman/listinfo/qt-interest

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20090527/50a14cb1/attachment.html 


More information about the Qt-interest-old mailing list