473,809 Members | 2,791 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Anyone mind reviewing my code?

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

int main(void)
{
unsigned int mask;
int a = -1;
mask = 1u << (CHAR_BIT * sizeof mask - 1);
while(mask) {
putchar(a & mask ? '1' : '0');
mask>>=1u;
}

putchar('\n');

return 0;
}

I was wanting to display the underlying representation
of signed and unsigned integers. I don't think I am
invoking undefined behavior but if I am, could someone
point it out?

Also, I can only use integer types with bitwise AND
And this is a convenient way of testing against
a mask. So how would one determine the bits
set in a float or double type to display the
underlying representation in binary?

I thought about using the examples from a
previously similar question I asked.
Where the examples given displayed the bytes in hex
I was thinking maybe I could display each individual
byte by displaying those bytes in binary consecutively.
But maybe there is a more clever way?
Nov 13 '05 #1
7 1563

On Thu, 2 Oct 2003, Mantorok Redgormor wrote:

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

int main(void)
{
unsigned int mask;
int a = -1;
mask = 1u << (CHAR_BIT * sizeof mask - 1);
Undefined behavior if 'unsigned int' has any
padding bits, I think. At best, it's
implementation-defined behavior.

I believe

mask = ~0u ^ (~0u >> 1)

is guaranteed correct, although I could be
mistaken. In general, this kind of bit-twiddling
is highly representation-specific, since who
in their right minds would write bit-twiddling
code like this that *needed* to run on two different
architectures?
while(mask) {
putchar(a & mask ? '1' : '0');
mask>>=1u;
}
It would be even more portable to forget the bit
twiddling entirely, and use a recursive approach:

void print_bits(unsi gned int x)
{
if (x != 0) print_bits(x/2);
printf("%d", x&1);
}
print_bits(a);

Exercise: Modify the above function to take an argument
saying how many bits to print in all.
putchar('\n');

return 0;
}
Also, I can only use integer types with bitwise AND
And this is a convenient way of testing against
a mask. So how would one determine the bits
set in a float or double type to display the
underlying representation in binary?
Examine it as an array of 'unsigned char':

double real = 3.141593;
unsigned char *representation = (unsigned char *)&real;
...
I thought about using the examples from a
previously similar question I asked.
Where the examples given displayed the bytes in hex
I was thinking maybe I could display each individual
byte by displaying those bytes in binary consecutively.
But maybe there is a more clever way?


Nope. :-)

-Arthur
Nov 13 '05 #2
"Arthur J. O'Dwyer" <aj*@nospam.and rew.cmu.edu> wrote in message news:<Pi******* *************** ************@un ix44.andrew.cmu .edu>...
On Thu, 2 Oct 2003, Mantorok Redgormor wrote:

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

int main(void)
{
unsigned int mask;
int a = -1;
mask = 1u << (CHAR_BIT * sizeof mask - 1);
Undefined behavior if 'unsigned int' has any
padding bits, I think.


Correct.
At best, it's implementation-defined behavior.

I believe

mask = ~0u ^ (~0u >> 1)
I'm partial to...

mask = -1u/2+1;

is guaranteed correct, although I could be
mistaken. In general, this kind of bit-twiddling
is highly representation-specific,
How many variant representations for unsigned types do you think there
are? As far as the value bits are concerned, there is only one, 'pure
binary'.
since who
in their right minds would write bit-twiddling
code like this that *needed* to run on two different
architectures?


People implementing portable encryption or coding theory algorithms
for one.

But, dumping bit-sets in most to least-significant order is not that
uncommon, or at least, I wouldn't have thought so.

--
Peter
Nov 13 '05 #3
Mantorok Redgormor wrote:
mask>>=1u;


That letter 'u' there doesn't help.
It doesn't hurt, but it doesn't help.

--
pete
Nov 13 '05 #4

On Thu, 2 Oct 2003, Peter Nilsson wrote:

"Arthur J. O'Dwyer" <aj*@nospam.and rew.cmu.edu> wrote...
On Thu, 2 Oct 2003, Mantorok Redgormor wrote:

mask = 1u << (CHAR_BIT * sizeof mask - 1);

[Something else...]
is guaranteed correct, although I could be
mistaken. In general, this kind of bit-twiddling
is highly representation-specific,
How many variant representations for unsigned types do you think there
are? As far as the value bits are concerned, there is only one, 'pure
binary'.


True. I had forgotten for a moment we were talking unsigned.
However, the numbers of value bits and padding bits are still
part of the implementation-defined representation.
since who
in their right minds would write bit-twiddling
code like this that *needed* to run on two different
architectures?


People implementing portable encryption or coding theory algorithms
for one.


While you may have a point, I think far more encryption schemes
will *assume* 32-bit 'int' or 8-bit 'char', and work with those.
Also, real code does not resort to weird bit-twiddling hacks to
produce values like 0x80000000; you'd simply write that value,
if that's what you meant. Or parameterize your coding algorithm
to specify the width of the data type being coded.
But, dumping bit-sets in most to least-significant order is not that
uncommon, or at least, I wouldn't have thought so.


True. That's why I gave the _portable_, recursive,
non-bit-twiddling solution.

-Arthur

Nov 13 '05 #5
On Thu, 2 Oct 2003 17:59:05 -0400 (EDT), "Arthur J. O'Dwyer"
<aj*@nospam.and rew.cmu.edu> wrote:

On Thu, 2 Oct 2003, Mantorok Redgormor wrote: <unsnip> I was wanting to display the underlying representation
of signed and unsigned integers. I don't think I am
invoking undefined behavior but if I am, could someone
point it out? </>
Note that none of these really display the underlying representation.
Where they work at all they display the value bits of the unsigned
value, which are (by requirement) much though possibly not all of the
representation; or of the signed value converted to unsigned, which
need not be so, although on two's-complement systems, the overwhelming
majority by far today, they are.

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

int main(void)
{
unsigned int mask;
int a = -1;
mask = 1u << (CHAR_BIT * sizeof mask - 1);


Undefined behavior if 'unsigned int' has any
padding bits, I think. At best, it's
implementation-defined behavior.

Not undefined. Shifts, like all other arithmetic operations, on
unsigned (integer) types, are well-defined. In this case, if there
are padding bits, which is i-d, the computed value will be reduced
modulo (UINT_MAX+1) to zero, which is useless.
I believe

mask = ~0u ^ (~0u >> 1)

is guaranteed correct, although I could be
mistaken. In general, this kind of bit-twiddling
is highly representation-specific, since who
in their right minds would write bit-twiddling
code like this that *needed* to run on two different
architectures?

If you really did look at the representation, that is one type,
perhaps the only type, of bit twiddling where you would have a real
need to run on different platforms.
while(mask) {
putchar(a & mask ? '1' : '0');
mask>>=1u;
}


It would be even more portable to forget the bit
twiddling entirely, and use a recursive approach:

void print_bits(unsi gned int x)
{
if (x != 0) print_bits(x/2);
printf("%d", x&1);
}

Or x%2 to avoid the bitwise operators altogether and be symmetric with
/, although for unsigned types and a power of two any decent compiler
on any non-brain-damaged platform will still implement as bit ops.

And more direct and probably more efficient, putchar( x%2 +'0').

<snip>
Also, I can only use integer types with bitwise AND
And this is a convenient way of testing against
a mask. So how would one determine the bits
set in a float or double type to display the
underlying representation in binary?


Examine it as an array of 'unsigned char':

double real = 3.141593;
unsigned char *representation = (unsigned char *)&real;
...

Right.

- David.Thompson1 at worldnet.att.ne t
Nov 13 '05 #6
"Dave Thompson" <da************ *@worldnet.att. net> wrote in message
news:c5******** *************** *********@4ax.c om...
On Thu, 2 Oct 2003 17:59:05 -0400 (EDT), "Arthur J. O'Dwyer"
<aj*@nospam.and rew.cmu.edu> wrote:
unsigned int mask;
mask = 1u << (CHAR_BIT * sizeof mask - 1);


Undefined behavior if 'unsigned int' has any
padding bits, I think. At best, it's
implementation-defined behavior.

Not undefined. Shifts, like all other arithmetic operations, on
unsigned (integer) types, are well-defined. In this case, if there
are padding bits, which is i-d, the computed value will be reduced
modulo (UINT_MAX+1) to zero, which is useless.


Sorry Dave, you missed the first semantic paragraph...

Bitwise shift operators
...
The integral promotions are performed on each of the operands. The
type of the result is that of the promoted left operand. If the value
of the right operand is negative or is greater than or equal to the
width in bits of the promoted left operand, the behavior is undefined.

Note the term 'width' is defined earlier as sign + value bits.

--
Peter
Nov 13 '05 #7
On Mon, 6 Oct 2003 17:37:22 +1000, "Peter Nilsson" <ai***@acay.com .au>
wrote:
"Dave Thompson" <da************ *@worldnet.att. net> wrote in message
news:c5******** *************** *********@4ax.c om... <snip>
> mask = 1u << (CHAR_BIT * sizeof mask - 1);
<snip> Not undefined. <snip>

Sorry Dave, you missed the first semantic paragraph... <snip>


Argh! I didn't miss it, I just forgot it. Sorry.

- David.Thompson1 at worldnet.att.ne t
Nov 13 '05 #8

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

Similar topics

11
2571
by: Arthur T. Murray | last post by:
Now, suppose that you wanted to write an AI in Python that would implement your mind-model and allow it to grow, mutate, develop. Here is one possible scenario. It would not be necessary to do all the work yourself. If we began coding a baby Mind.py and published the initial code out on the Web, other Python programmers might start adding to it and start specializing in the refinement of hotspots. ...
6
6162
by: Danny Lesandrini | last post by:
I'm using an Access database to drive a web site and the colors of various table backgrounds are stored in Access. I want users of the Access database to be able to select colors for the site, but my mappings between named colors, HEX values and the Long Integer values used in Access are not jibbing. Anyone have a nice list laying around? Danny J Lesandrini dlesandrini@hotmail.com
1
1791
by: Rob R. Ainscough | last post by:
I'm at a new level of frustration just trying to get my controls to line up and stay in place. I'm using a MultiView containing 4 views - some views have Panels. I can't use absolution position on my controls because in MultiView that means when the views are switched (ActiveViewIndex) the controls in the new view are absolution position which means they are displayed lower down the page (where they were arranged in the original view...
13
2266
by: Snis Pilbor | last post by:
Hello, Here is an idea I've been toying with to speed up programs but still keep them portable. It's just a very handwavey rough description right now since I haven't worked out details. The program would contain lots of little utility functions which do small amounts of work. None of these would actually be run. Rather, they would be typecast as strings and those strings would be examined by the program. In otherwords, the...
66
5423
by: genestarwing | last post by:
QUESTION: Write a program that opens and read a text file and records how many times each word occurs in the file. Use a binary search tree modified to store both a word and the number of times it occurs. After the program has read the file, it should offer a menu with three choices. the first is to list all the words along with the number of occurences. The second is to let you enter a word, with the program reporting how many times the...
3
1314
by: MrHelpMe | last post by:
Hello experts and thanks so much for having a look at this. I have the following peice of code that I am stumped on. <table width="90%" cellpadding=0 align="center"> <tr> <td align="left"><font face="arial,helvetica" size=4 Color = "8CB811"><b><%= Trim(objRS("Category")) %></b></font></td> </tr> <%
169
9230
by: JohnQ | last post by:
(The "C++ Grammer" thread in comp.lang.c++.moderated prompted this post). It would be more than a little bit nice if C++ was much "cleaner" (less complex) so that it wasn't a major world wide untaking to create a toolchain for it. Way back when, there used to be something called "Small C". I wonder if the creator(s) of that would want to embark on creating a nice little Small C++ compiler devoid of C++ language features that make...
1
1221
by: DivyaSindhu | last post by:
hi there..... I need to review the javascript which is running thousands of lines can you please suggest me some good reviewing tools for java script. please let me know in case there are some free tools available
3
1602
by: JeanDean | last post by:
I am looking for freeware tool which can review the c++ code(compiled on g++). Please share your experiences and details obout the usage of the tool.
0
9601
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
10635
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
10376
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...
0
10115
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
9198
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4332
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
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3013
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.