Sign in to follow this  

Bit into a Byte

This topic is 3665 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Here is my code so far. All I did was take one line of your code and made ( more like tried to it seems ) it compatible with my own. The only function that matters is BExpand. Sorry for the undo fustration. #include <stdio.h> #include <conio.h> void BExpand (unsigned char *results, int length, unsigned int bits) { *results = ( bits >> length ) & 1; } void PrintBinary (unsigned char *results, int length) { //Represents nibble length; used for spacing. unsigned int NIBBLE_LENGTH = 0; //Variable used to iterate through for loop. int Iterator = 0; //For each bit... for ( ; Iterator < length; Iterator++ ) { //...Print a one to screen if the bit is on, or a zero to screen if it is off... *results & ( 1 << Iterator ) ? printf ( "%d", 1 ) : printf ( "%d", 0 ); //...If the length of a nibble has been reached, print a space. NIBBLE_LENGTH == 3 ? printf ( " " ), NIBBLE_LENGTH = 0 : NIBBLE_LENGTH++; }; //If we have not completed a nibble... if ( Iterator % 4 != 0 ) { do { //...print a dash... printf ( "-" ); //...and increment the iterator... Iterator++; //...until we have finished the nibble. } while ( Iterator % 4 != 0 ); }; //Insert a new line when we are done. printf("\n"); } void main() { unsigned char data [32]; unsigned int bits = 0xDEADBEEFL; int len; for (len = 32; len > 0; len -= 7) { BExpand (data, len, bits); PrintBinary (data, len); } _getch(); }

Share this post


Link to post
Share on other sites
BExpand modifies the character pointed to by 'results' (a silly name) to be equal to 1 if the bit at 'length' (another silly name) is 1. A better implementation would be:
char IsSet(unsigned offset, unsigned bits)
{
return (bits >> offset) & 1;
}


Then, transforming a list of bits into an unsigned number is to be done bit by bit.
void ToChar(const char (*target)[32], unsigned bits)
{
for (int i = 0; i < 32; ++i)
(*target)[i] = IsSet(i,bits);
}

Share this post


Link to post
Share on other sites

This topic is 3665 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Guest
This topic is now closed to further replies.
Sign in to follow this