Bit twiddling
- From: grid <prohit99@xxxxxxxxx>
- Date: Wed, 01 Jun 2005 20:04:29 +0530
Hi,
I have written a couple of programs which just prints the bits in both directions.Would appreciate any help to refine them a bit.
1.
#include<stdio.h>
#include<limits.h>
void printbits_reverse(unsigned char a){
int i;
for(i=0 ; i < CHAR_BIT ; i++)
((0x1<<i) & a) ? printf("1") : printf("0"); }
int main()
{
unsigned char a = 0x96;
printbits_reverse(a);
return 0;
}Now here the loop dosent look the best of code.How can I refine it to better and generic code ?
2.
#include<stdio.h>
struct twid{
unsigned :24; /* skip bits 31 -> 8 for big-endian machines */
unsigned bit1:1;
unsigned bit2:1;
unsigned bit3:1;
unsigned bit4:1;
unsigned bit5:1;
unsigned bit6:1;
unsigned bit7:1;
unsigned bit8:1;
};void print(struct twid *tw)
{
tw->bit1?printf("1"):printf("0");
tw->bit2?printf("1"):printf("0");
tw->bit3?printf("1"):printf("0");
tw->bit4?printf("1"):printf("0");
tw->bit5?printf("1"):printf("0");
tw->bit6?printf("1"):printf("0");
tw->bit7?printf("1"):printf("0");
tw->bit8?printf("1"):printf("0");
printf("\n");
}int main()
{
unsigned val = 0x96;
struct twid *tw = (struct twid *) &val ;
print(tw);
return 0;
}This is not a generic code ( a bit platform specific), but that long list of printf's in the print function isnt again a very decent way.Can I use a loop or any construct to print the values ?
TIA, .
- Follow-Ups:
- Re: Bit twiddling
- From: grid
- Re: Bit twiddling
- From: Paul Mesken
- Re: Bit twiddling
- From: pete
- Re: Bit twiddling
- Prev by Date: Re: pointers and integers
- Next by Date: Re: pointers and integers
- Previous by thread: merging list problem
- Next by thread: Re: Bit twiddling
- Index(es):