473,398 Members | 2,088 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

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 1542

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(unsigned 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.andrew.cmu.edu> wrote in message news:<Pi**********************************@unix44. 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.andrew.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.andrew.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(unsigned 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.net
Nov 13 '05 #6
"Dave Thompson" <da*************@worldnet.att.net> wrote in message
news:c5********************************@4ax.com...
On Thu, 2 Oct 2003 17:59:05 -0400 (EDT), "Arthur J. O'Dwyer"
<aj*@nospam.andrew.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.com... <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.net
Nov 13 '05 #8

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

Similar topics

11
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...
6
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...
1
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...
13
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...
66
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...
3
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...
169
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...
1
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...
3
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
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
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,...
0
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.