473,804 Members | 3,057 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Bit twiddling

Hi,
I have written a couple of programs which just prints the bits in
both directions.Woul d appreciate any help to refine them a bit.

1.
#include<stdio. h>
#include<limits .h>
void printbits_rever se(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_rever se(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,
Nov 14 '05 #1
40 2004
grid wrote:

Hi,
I have written a couple of programs which just prints the bits in
both directions.Woul d appreciate any help to refine them a bit.

1.
#include<stdio. h>
#include<limits .h>
void printbits_rever se(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_rever se(a);
return 0;
}

Now here the loop dosent look the best of code.How can I refine it to
better and generic code ?


#include<stdio. h>
#include<limits .h>

void printbits_rever se(unsigned char a);
void bit_str(char *s1, const void *s2, size_t n);
unsigned char bit_rev(unsigne d char byte);

int main(void)
{
unsigned char a = 0x96;

printbits_rever se(a);
return 0;
}

void printbits_rever se(unsigned char a)
{
char string[CHAR_BIT + 1];

a = bit_rev(a);
bit_str(string, &a, 1);
puts(string);
}

void bit_str(char *s1, const void *s2, size_t n)
{
unsigned mask;
const unsigned char *const byte = s2;

while (n-- != 0) {
mask = ((unsigned char)-1 >> 1) + 1;
do {
*s1++ = (char)(mask & byte[n] ? '1' : '0');
mask >>= 1;
} while (mask != 0);
}
*s1 = '\0';
}

unsigned char bit_rev(unsigne d char byte)
{
unsigned hi_mask, lo_mask;

hi_mask = ((unsigned char)-1 >> 1) + 1;
lo_mask = 1;
do {
if (!(byte & hi_mask) != !(byte & lo_mask)) {
byte ^= hi_mask | lo_mask;
}
hi_mask >>= 1;
lo_mask <<= 1;
} while (hi_mask > lo_mask);
return byte;
}
Nov 14 '05 #2
On Wed, 01 Jun 2005 20:04:29 +0530, grid <pr******@gmail .com> wrote:
Hi,
I have written a couple of programs which just prints the bits in
both directions.Woul d appreciate any help to refine them a bit.

1.
#include<stdio .h>
#include<limit s.h>
void printbits_rever se(unsigned char a){
int i;
for(i=0 ; i < CHAR_BIT ; i++)
((0x1<<i) & a) ? printf("1") : printf("0"); }
Oh, I don't think it's too bad but an obvious optimization would be to
make a string (instead of printing each digit individually) and then
print that string.

void printbits_rever se(unsigned char a)
{
int i;
char MyBitstring[CHAR_BIT + 1];

for (i = 0; i < CHAR_BIT; ++ i)
{
if (a & 1)
MyBitstring[i] = '1';
else
MyBitstring[i] = '0';
a >>= 1;
}
MyBitstring[CHAR_BIT] = '\0';
printf("%s", MyBitstring);
return;
}

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 ?


It's ugly, unportable and relies on unspecified behaviour (you cannot
know whether bitfields are laid out from left to right or vice versa).

Nov 14 '05 #3
On Wed, 01 Jun 2005 17:32:37 +0200, Paul Mesken <us*****@eurone t.nl>
wrote:
void printbits_rever se(unsigned char a)
{
int i;
char MyBitstring[CHAR_BIT + 1];

for (i = 0; i < CHAR_BIT; ++ i)
{
if (a & 1)
MyBitstring[i] = '1';
else
MyBitstring[i] = '0';
a >>= 1;
}
MyBitstring[CHAR_BIT] = '\0';
printf("%s", MyBitstring);
return;
}


By the way, just for fun :

for (i = 0; i < CHAR_BIT; ++ i)
{
MyBitstring[i] = '0' + (a & 1);
a >>= 1;
}

But I don't know whether '1' is 1 greater than '0' in every character
set that C supports (but it's okay for both EBCDIC and ASCII).
Nov 14 '05 #4
In article <2v************ *************** *****@4ax.com>,
Paul Mesken <us*****@eurone t.nl> wrote:
But I don't know whether '1' is 1 greater than '0' in every character
set that C supports (but it's okay for both EBCDIC and ASCII).


Yes, that is a requirement in the standard. Sequentially increasing
digits is the -only- ordering requirements that the C89 standard
imposes on the character set.

--
Usenet is like a slice of lemon, wrapped around a large gold brick.
Nov 14 '05 #5
On 1 Jun 2005 17:23:09 GMT, ro******@ibd.nr c-cnrc.gc.ca (Walter
Roberson) wrote:
In article <2v************ *************** *****@4ax.com>,
Paul Mesken <us*****@eurone t.nl> wrote:
But I don't know whether '1' is 1 greater than '0' in every character
set that C supports (but it's okay for both EBCDIC and ASCII).


Yes, that is a requirement in the standard. Sequentially increasing
digits is the -only- ordering requirements that the C89 standard
imposes on the character set.


Yes, you're right :

5.2.1 Character Sets

..... In both the source and execution basic character sets, the value
of each character after '0' in the above list of decimal digits shall
be one greater than the value of the previous....

Well, in that case : go for the second solution, Grid :-)

Nov 14 '05 #6
Paul Mesken wrote:
grid <pr******@gmail .com> wrote:
I have written a couple of programs which just prints the bits in
both directions.Woul d appreciate any help to refine them a bit.
.... snip ...
Oh, I don't think it's too bad but an obvious optimization would be
to make a string (instead of printing each digit individually) and
then print that string.


It's just printing a number in base 2. In the last day or two I
posted a routine to output numbers to streams in various bases.
Search for unum2txt.

--
"I conclude that there are two ways of constructing a software
design: One way is to make it so simple that there are obviously
no deficiencies and the other way is to make it so complicated
that there are no obvious deficiencies." -- C. A. R. Hoare
Nov 14 '05 #7
Paul Mesken wrote:
grid wrote:
#include<stdi o.h>
#include<limi ts.h>
void printbits_rever se(unsigned char a){
int i;
for(i=0 ; i < CHAR_BIT ; i++)
((0x1<<i) & a) ? printf("1") : printf("0"); }


Oh, I don't think it's too bad but an obvious optimization would be to
make a string (instead of printing each digit individually) and then
print that string.


Is that really an optimisation? It uses more memory, and stdout
is probably buffered anyway.

This solution 'optimises' by using putchar instead of printf (surely
that must be at least as fast), and is still as concise as the
original:

for (i = 0; i < CHAR_BIT; i++)
putchar( ((1 << i) & a) ? '1' : '0' );
putchar('\n');

Nov 14 '05 #8
On 1 Jun 2005 18:52:47 -0700, "Old Wolf" <ol*****@inspir e.net.nz>
wrote:
Paul Mesken wrote:
grid wrote:
#include<std io.h>
#include<lim its.h>
void printbits_rever se(unsigned char a){
int i;
for(i=0 ; i < CHAR_BIT ; i++)
((0x1<<i) & a) ? printf("1") : printf("0"); }
Oh, I don't think it's too bad but an obvious optimization would be to
make a string (instead of printing each digit individually) and then
print that string.


Is that really an optimisation? It uses more memory, and stdout
is probably buffered anyway.


Reducing the amount of calls (especially to big ones, like printf) is,
typically, an optimization (reducing the overhead that may accompany
the calls). Although this might not hold for functions that are very
small and are inlined by the compiler but I don't believe printf is
inlined. I wouldn't worry too much about the extra memory used by an
array of CHAR_BIT + 1 chars :-)
This solution 'optimises' by using putchar instead of printf (surely
that must be at least as fast), and is still as concise as the
original:

for (i = 0; i < CHAR_BIT; i++)
putchar( ((1 << i) & a) ? '1' : '0' );
putchar('\n');


This is better than the OPs printf function, but IMHO not better than
my second version (adding "a & 1" to '0') which eliminates the
implicit "if-else" of the "?:" operator and only one call to printf.

Nov 14 '05 #9
> 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");


Is there any way to traverse through the member bitfields with a loop or
is there a consise way to write the above stuff.

TIA
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

58
4702
by: Jeff_Relf | last post by:
Hi Tom, You showed: << private const string PHONE_LIST = "495.1000__424.1111___(206)564-5555_1.800.325.3333"; static void Main( string args ) { foreach (string phoneNumber in Regex.Split (PHONE_LIST, "_+")) { Console.WriteLine (phoneNumber); } } Output: 495.1000
5
2246
by: matobinder | last post by:
I need to write some code that deals with some memory images. In essence, these images are just a collection of data, integers, bools, floats, and so on. The mucky part with this case is that nothing falls on byte boundries, so I can't just use the ostream::write() stuff... Let me quick explain this with an simple example. I have an image data length of 2 bytes.
3
1516
by: Derek | last post by:
I have an application that creates lots of small objects that represent a 2D axis-parallel plane. In short, I these little objects look like this: struct Plane { float location; enum { X, Y, Z } direction; }; On my 32-bit platform this structure is 8 bytes, 4 of which
7
1842
by: Jeff.Goldfinkle | last post by:
Hi All Is there a simple way to twiddle the bits of a float? In particular, I would like to round my float to the n most significant bits. For example - 0.123 in binary is 0.000111111 Rounding to 4 bits I get 0.0001. I can pack and unpack a float into a long e.g.
0
9584
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10583
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10337
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10323
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10082
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6854
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4301
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3822
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2995
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.