From -4721305051976748649
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: f78e5,290ced9644daa112
X-Google-Attributes: gidf78e5,public
From: msherman@magma.ca (Marc Sherman)
Subject: Re: Types with Bit-Sizes
Date: 1998/03/16
Message-ID: <6eh08r$hon@shell.magma.ca>#1/1
X-Deja-AN: 334494203
References: <35084BDC.4108978E@verisim.com> <35097536.2781@wizard.net>
X-Original-Date: 15 Mar 1998 11:39:55 -0500
Reply-To: msherman@magma.ca
Organization: Magma Communications Ltd., Nepean, Ontario, Canada
X-Auth: PGPMoose V1.1 PGP comp.std.c++ iQBFAgUANQz66uEDnX0m9pzZAQFKGgF/UpeINTQ7aeHXvww5b+H2Bdr3lOU/Rn/G D/TuGK4ZdLHxbh42dMFhTKWxkDCYi8q4 =ZNPQ
Newsgroups: comp.std.c++


In article <35097536.2781@wizard.net>, James Kuyper  <kuyper@wizard.net> wrote:
>Brian White wrote:
>> 
>> Is there anything in the the ANSI C++ spec that provides for datatypes of
>> known bit sizes?

The following declarations can be used in ANSI C++ code (I think - please
correct me if I've made a mistake!) to get an int of a known size.  To get
a signed integral type of exactly 16 bits, use
  sized_int<16,true>::int_t
and to get an unsigned integral type of at least 19 bits, use
  sized_int<19,false>::int_min_t

Code follows:
#include <climits>

template <size_t TSizeInBits, bool TSigned>
struct sized_int
{ typedef sized_int<TSizeInBits+1, TSigned>::int_min_t int_min_t; };

// Specialize for a very large value (max size_t) to ensure that
// when trying to get an int_min_t larger than the largest int type
// on this machine, the recursion ends.  In practice, it will end
// much earlier with a compiler error due to template recursion limits.
template<bool TSigned>
struct sized_int<ULONG_MAX, TSigned> {};


#define SPECIALIZE_SIZED_INT(TYPE) \
template<> struct sized_int<sizeof(signed TYPE) * CHAR_BIT, true> \
	{ typedef signed TYPE int_t; typedef signed TYPE int_min_t; }; \
template<> struct sized_int<sizeof(unsigned TYPE) * CHAR_BIT, false> \
	{ typedef unsigned TYPE int_t; typedef unsigned TYPE int_min_t; }

// Specialize for char
SPECIALIZE_SIZED_INT(char);

// Specialize for short if it's bigger than char
#if (USHRT_MAX > UCHAR_MAX)
	SPECIALIZE_SIZED_INT(short);
#endif

// Specialize for int if it's bigger than short
#if (UINT_MAX > USHRT_MAX)
	SPECIALIZE_SIZED_INT(int);
#endif

// Specialize for long if it's bigger than int
#if (ULONG_MAX > UINT_MAX)
	SPECIALIZE_SIZED_INT(long);
#endif

// Specialize for long long if it exists and it's bigger than int
#if defined(ULONGLONG_MAX) && (ULONGLONG_MAX > ULONG_MAX)
	SPECIALIZE_SIZED_INT(long long);
#endif

#undef SPECIALIZE_SIZED_INT

- Marc
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]



