473,766 Members | 2,120 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Value bits as compile-time constant!

Over on comp.lang.c, Hallvard B Furuseth devised a compile-time constant
representing the amount of value representation bits in an unsigned
integer type. In true C fashion, here it is as a macro:
/* Number of bits in inttype_MAX, or in any (1<<k)-1 where 0 <= k < 3.2E+
10 */
#define IMAX_BITS(m) ((m) /((m)%0x3fffffff L+1) /0x3fffffffL %0x3fffffffL
*30 \
+ (m)%0x3fffffffL /((m)%31+1)/31%31*5 + 4-12/((m)%
31+3))
You supply it with an unsigned integer value whose bit-pattern consists
of all 1's, e.g.:

1 (Decimal: 1)
11 (Decimal: 3)
111 (Decimal: 7)
11111111 (Decimal: 255)
To find out the amount of value bits in an unsigned integer type, you
supply it with that type's max value (i.e. a bit pattern of all 1's). The
handiest way to get the max value of an unsigned integer type is to
assign -1 to it:

unsigned const max_value = -1;

unsigned const amount_value_bi ts = IMAX_BITS( max_value );
Here's some template code I've written which makes use of it:
template<class T>
struct IMaxBits {

template<T m>
struct AllOnes {

static unsigned const val =
m /(m%0x3fffffffL+ 1) /0x3fffffffL %0x3fffffffL *30
+ m%0x3fffffffL /(m%31+1)/31%31*5 + 4-12/(m%31+3);

};

};
template<class T>
struct AmountValueBits {

static unsigned const val = IMaxBits<T>::te mplate AllOnes<-1>::val;

};
#include <cstdlib>
#include <cstring>
#include <cstddef>
#include <cassert>

template<std::s ize_t width>
inline const char* CenterHoriz( const char * const p )
{
using std::memset;
using std::strlen;
using std::size_t;

static char spaces[width + 1];
memset( spaces, ' ', width );

size_t const len = strlen( p );

assert( width >= len );
char * const pos = spaces + ( width / 2 - len / 2 );
memcpy( pos, p, len );

return spaces;
}

#include <iostream>

extern char const str_uchar[] = "unsigned char";
extern char const str_ushort[] = "unsigned short";
extern char const str_uint[] = "unsigned int";
extern char const str_ulong[] = "unsigned long";

template<class T, const char* str>
void PrintRow()
{
using std::cout;

unsigned const total_bits = sizeof(T) * AmountValueBits <unsigned
char>::val;
unsigned const val_bits = AmountValueBits <T>::val;
unsigned const pad_bits = total_bits - val_bits;

const char * const spaces_val =
val_bits > 99 ? "" : ( val_bits > 9 ? " " : " " );

const char * const spaces_pad =
pad_bits > 99 ? "" : ( pad_bits > 9 ? " " : " " );

const char * const spaces_total =
total_bits > 99 ? "" : ( total_bits > 9 ? " " : " " );
cout << "||" << CenterHoriz<21> (str) << "|| "
<< spaces_val << val_bits << " || " << spaces_pad <<
pad_bits
<< " || " << spaces_total << total_bits << " ||\n"

"---------------------------------------------------------------------
\n";
}

int main()
{
using std::cout;

cout <<

"
=============== =============== =============== =\n"
" || Value bits || Padding Bits || Total Bits
||\n"

"============== =============== =============== =============== ==========
\n";

PrintRow<unsign ed char, str_uchar>();
PrintRow<unsign ed short, str_ushort>();
PrintRow<unsign ed, str_uint>();
PrintRow<unsign ed long, str_ulong>();

cout << "\n\n\n";

std::system( "PAUSE" );
}

I'd be interested to hear if anyone gets some "interestin g" values.

--

Frederick Gotham
Jun 25 '06 #1
12 2260
* Frederick Gotham:
Over on comp.lang.c, Hallvard B Furuseth devised a compile-time constant
representing the amount of value representation bits in an unsigned
integer type. In true C fashion, here it is as a macro:
/* Number of bits in inttype_MAX, or in any (1<<k)-1 where 0 <= k < 3.2E+
10 */
#define IMAX_BITS(m) ((m) /((m)%0x3fffffff L+1) /0x3fffffffL %0x3fffffffL
*30 \
+ (m)%0x3fffffffL /((m)%31+1)/31%31*5 + 4-12/((m)%
31+3))


In C++ you'd use std::numeric_li mits::digits instead.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jun 25 '06 #2

"Frederick Gotham" <fg*******@SPAM .com> wrote in message
news:Xn******** *************** ****@194.125.13 3.14...
Over on comp.lang.c, Hallvard B Furuseth devised a compile-time constant
representing the amount of value representation bits in an unsigned
integer type. In true C fashion, here it is as a macro:


What does this mean: "the amount of value representation bits"?

-Howard
Jun 26 '06 #3
Howard wrote:
"Frederick Gotham" <fg*******@SPAM .com> wrote in message
news:Xn******** *************** ****@194.125.13 3.14...
Over on comp.lang.c, Hallvard B Furuseth devised a compile-time
constant representing the amount of value representation bits in an
unsigned integer type. In true C fashion, here it is as a macro:


What does this mean: "the amount of value representation bits"?


Substitute 'amount' with 'number', does it make it simpler? If not,
substitue 'value representation' with 'value-representing'. If after
that it's not clear, then the definition is probably "the number of
bits involved in representing the value".

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 26 '06 #4
Howard posted:

What does this mean: "the amount of value representation bits"?

I'll work off an example.

Let's say that a byte is 8-Bit, and that sizeof(unsigned short) == 4.

Therefore, an "unsigned short" takes up 32 bits in memory.

But that doesn't mean an unsigned short can use 32 bits to store its value.
It might only use 30 of those bits; the rest are padding bits. The macro
yields a compile time constant telling us how many bits take part in the
"value representation" of the unsigned integer type.
--

Frederick Gotham
Jun 26 '06 #5

"Frederick Gotham" <fg*******@SPAM .com> wrote in message
news:Xn******** *************** ****@194.125.13 3.14...
Howard posted:

What does this mean: "the amount of value representation bits"?

I'll work off an example.

Let's say that a byte is 8-Bit, and that sizeof(unsigned short) == 4.

Therefore, an "unsigned short" takes up 32 bits in memory.

But that doesn't mean an unsigned short can use 32 bits to store its
value.
It might only use 30 of those bits; the rest are padding bits. The macro
yields a compile time constant telling us how many bits take part in the
"value representation" of the unsigned integer type.


Interesting. I don't recall ever hearing of padding bits in a stored
integer before (except perhaps way back in my old 60-bit Cyber mainframe
days...but those memories are fading). Do any modern machines actually have
them? All the machines I've worked with in recent years allow you to use
(for example) all 32 bits of a 32-bit integer. The CPU may contain extra
"flag" bits, but those don't reduce the amount useable in stored memory.

-Howard

Jun 26 '06 #6
Howard posted:

Interesting. I don't recall ever hearing of padding bits in a stored
integer before (except perhaps way back in my old 60-bit Cyber
mainframe days...but those memories are fading).

I think super-computers do it, something to do with "emphasizin g
floating-point arithmetic"...

All the machines I've worked with in
recent years allow you to use (for example) all 32 bits of a 32-bit
integer.

All the bits in memory belong to you, and they're yours to play around
with, e.g.:

unsigned short i;

unsigned char *p =
reinterpret_cas t<unsigned char*>( &i );

unsigned char * const p_over =
reinterpret_cas t<unsigned char*>( &i + 1 );
do
{
*p++ = 0;
} while( p != p_over );
But if you store a value as an unsigned short, then you don't have 2^32
unqiue values, but rather 2^30... even though it takes up 32 bits in
memory. It's all about range really:

0
through
( 2^(amount value bits) ) - 1
--

Frederick Gotham
Jun 26 '06 #7

"Frederick Gotham" <fg*******@SPAM .com> wrote in message
news:Xn******** *************** ****@194.125.13 3.14...
Howard posted:

Interesting. I don't recall ever hearing of padding bits in a stored
integer before (except perhaps way back in my old 60-bit Cyber
mainframe days...but those memories are fading).

I think super-computers do it, something to do with "emphasizin g
floating-point arithmetic"...

All the machines I've worked with in
recent years allow you to use (for example) all 32 bits of a 32-bit
integer.

All the bits in memory belong to you, and they're yours to play around
with, e.g.:

unsigned short i;

unsigned char *p =
reinterpret_cas t<unsigned char*>( &i );

unsigned char * const p_over =
reinterpret_cas t<unsigned char*>( &i + 1 );
do
{
*p++ = 0;
} while( p != p_over );
But if you store a value as an unsigned short, then you don't have 2^32
unqiue values, but rather 2^30... even though it takes up 32 bits in
memory. It's all about range really:

0
through
( 2^(amount value bits) ) - 1


(Assuming unsigned short is 30 bits, I guess. On my PC, it's 16 bits, and I
think on my Mac as well.)

Thanks,
-Howard


Jun 26 '06 #8
* Howard:

(Assuming unsigned short is 30 bits, I guess. On my PC, it's 16 bits, and I
think on my Mac as well.)


Go back up the thread to find the context for the example.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jun 26 '06 #9
In article <KZUng.62753$mF 2.33728@bgtnsc0 4-
news.ops.worldn et.att.net>, al*****@hotmail .com says...

[ ... ]
Interesting. I don't recall ever hearing of padding bits in a stored
integer before (except perhaps way back in my old 60-bit Cyber mainframe
days...
Yup -- 40 significant bits and 20 padding bits.
but those memories are fading).
If you ever want to look at it, _Design of a Computer: The Control
Data 6600_, by James Thornton has been scanned in and is available
for download a number of places around the 'net. If you're ever
struck with a _reallY_ serious bout of nostalgia, check out:
http://members.iinet.net.au/~tom-hunter/
the "Desktop Cyber emulator home." It's almost even close to topical,
being written in portable C.
Do any modern machines actually have
them? All the machines I've worked with in recent years allow you to use
(for example) all 32 bits of a 32-bit integer. The CPU may contain extra
"flag" bits, but those don't reduce the amount useable in stored memory.


I've seen a compiler for a 12-bit DSP that stored char as 8
significant bits with 4 padding bits. That was a few years ago
though. In the last few years, DSPs have started to look quite a bit
more like mainstream CPUs (while CPUs have started to look a bit more
like DSPs).

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 26 '06 #10

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

Similar topics

3
1424
by: JKop | last post by:
Consider the following platform: char = 8-bit short = 16-bit int = 32-bit long = 32-bit
30
1584
by: Alf P. Steinbach | last post by:
The C++ FAQ item 29.5 (this seems to be strongly related to C), at <url: http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.5> mentions that <quote> C++ guarantees a char is exactly one byte which is at least 8 bits, short is at least 16 bits, int is at least 16 bits, and long is at least 32 bits. </quote>
29
16838
by: Peter Ammon | last post by:
What's the most negative double value I can get? Is it always guaranteed to be -DBL_MAX? If so, why (or rather, where)? Thanks.
13
1801
by: Steve Edwards | last post by:
Hi, I have a class with some static variables: in MyClass.h //------------------------- lass MyClass{ .... public: static long myVals; // declaration
35
12580
by: Frederick Gotham | last post by:
I'm writing a template, and I need to know the maximum value of a given integer type at compile time. something like: template<class NumType> class Arb { public: static NumType const max = /* maximum value */; };
15
4852
by: steve yee | last post by:
i want to detect if the compile is 32 bits or 64 bits in the source code itself. so different code are compiled respectively. how to do this?
7
28039
by: anuragkhanna8 | last post by:
Hi, I am trying to convert a 16 bit rgb value to 32 bit, however the new color generated is different from the 16 bit rgb data. Please let me know the formula to convert an 16 bit rgb data to 32 bit rgb data. Thanks!!
7
6603
by: gene kelley | last post by:
I have an application where I need to read some header information found in 3 different types of file types. Two of the file types were fairly straight forward as the items to read in the header are at least 8 bits (one byte), so, I'm able to step through a file stream with a binary reader and retrive the data. The last file type, however, has me stumped at the moment. The header spec specifies the item lengths in bits. Most of the...
11
14667
by: Mack | last post by:
Hi all, I want to write a program to count number of bits set in a number. The condition is we should not loop through each bit to find whether its set or not. Thanks in advance, -Mukesh
69
3333
by: Horacius ReX | last post by:
Hi, I have the following program structure: main ..... int A=5; int* ptr= A; (so at this point ptr stores address of A) ..... .....
0
9404
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
10008
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
9959
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
9837
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...
1
7381
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6651
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();...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
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.