473,734 Members | 2,272 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Design, enums, and const ints

I have a home grown bit vector and I keep oscillating between what I use
access individual bits.

For example, is is better to do this:

const int BIT_1 = 1;
const int BIT_2 = 2;
....

int my_bits;

// Set bit 1
my_bits |= BIT_1;

Or, should I create an enum

enum BitPos
{
Bit1 = 1,
Bit2 = 2,
....
}

// Set bit 1
my_bits |= (int)BitPos.Bit 1;

--------------------------------------------------------

The explicit cast bothers me... any opinions as to how you might do this
would be appreciated!

-Reed
Dec 23 '05 #1
7 1544
Why not just make my_bits a BitPos variable instead of an int? Then you
won't need to cast every time you set or unset a bit.

Jesse

Dec 23 '05 #2
Hi,

Instead of using *enum* create a class with constants or static readonly
fields or properties of type *int* this way you don't have to cast.
--

Stoitcho Goutsev (100) [C# MVP]

"Bit Twiddler" <bi***********@ hotmail.com> wrote in message
news:es******** *****@tk2msftng p13.phx.gbl...
I have a home grown bit vector and I keep oscillating between what I use
access individual bits.

For example, is is better to do this:

const int BIT_1 = 1;
const int BIT_2 = 2;
...

int my_bits;

// Set bit 1
my_bits |= BIT_1;

Or, should I create an enum

enum BitPos
{
Bit1 = 1,
Bit2 = 2,
...
}

// Set bit 1
my_bits |= (int)BitPos.Bit 1;

--------------------------------------------------------

The explicit cast bothers me... any opinions as to how you might do this
would be appreciated!

-Reed

Dec 23 '05 #3
Thanks both to Jesse and Stoitcho for their responses.

I went with the static readonly field method (Jesse, they can't be simple
variables because their values must *not* change after they are
initialized).

In my specific case, object size is incredibly important, so creating
wrapper classes, etc. would incur too much memory overhead.

Thanks,
BT
"Stoitcho Goutsev (100) [C# MVP]" <10*@100.com> wrote in message
news:ee******** ******@TK2MSFTN GP09.phx.gbl...
Hi,

Instead of using *enum* create a class with constants or static readonly
fields or properties of type *int* this way you don't have to cast.
--

Stoitcho Goutsev (100) [C# MVP]

"Bit Twiddler" <bi***********@ hotmail.com> wrote in message
news:es******** *****@tk2msftng p13.phx.gbl...
I have a home grown bit vector and I keep oscillating between what I use
access individual bits.

For example, is is better to do this:

const int BIT_1 = 1;
const int BIT_2 = 2;
...

int my_bits;

// Set bit 1
my_bits |= BIT_1;

Or, should I create an enum

enum BitPos
{
Bit1 = 1,
Bit2 = 2,
...
}

// Set bit 1
my_bits |= (int)BitPos.Bit 1;

--------------------------------------------------------

The explicit cast bothers me... any opinions as to how you might do this
would be appreciated!

-Reed


Dec 23 '05 #4
Bit Twiddler <bi***********@ hotmail.com> wrote:
Thanks both to Jesse and Stoitcho for their responses.

I went with the static readonly field method (Jesse, they can't be simple
variables because their values must *not* change after they are
initialized).


I think you missed Jesse's point - he was suggesting that the variable
should be of the enum type rather than an int. In other words:

static readonly BitPos my_pos = ...;

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 23 '05 #5
Bit Twiddler wrote:
I went with the static readonly field method (Jesse, they can't be simple
variables because their values must *not* change after they are
initialized).


As Jon mentioned, you seem to have misunderstood me. I'm suggesting
something like this:

// declare an enum to hold the bit values
// the Flags attribute indicates that multiple values can be combined
[Flags]
enum BitPos {
None = 0,
Bit1 = 1,
Bit2 = 2,
Bit3 = 4,
// etc.
}

public void BitFieldDemo() {
// here is your bitfield
BitPos my_bits = BitPos.None;

// now let's set a bit
my_bits |= BitPos.Bit1;

// let's see if another bit is set
if ((my_bits & BitPos.Bit2) != 0)
Console.WriteLi ne("bit 2 is set - how did that happen?");
else
Console.WriteLi ne("good, bit 2 is not set");
}

Now you won't have to cast when you set, unset, or test bits. You will
have to cast if you need to convert my_bits to/from an int, though. One
benefit of using a [Flags] enum is you can call my_bits.ToStrin g() to
get a human-readable string like "Bit1, Bit3" instead of just a number.

Jesse

Dec 24 '05 #6
Thanks Jesse (and Jon). I *did* misunderstand you Jesse - thanks for the
clarification.

Let's say that I am using a BitVector32 to store my bits. The bits in a
BitVector32 are indexed like an array.

Since I have to use an int to index into the BitVector32 I need to create
things like this:

private static readonly int BIT_1 = BitVector32.Cre ateMask(); //
1st bit
private static readonly int BIT_2 = BitVector32.Cre ateMask(BIT_1); // 2nd
bit

I'm not a fan of static ints like that so I wanted to do something like
this:

private enum BitPos
{
Bit1 = 1.
Bit2,
....
}

But if I do that, and I want to index into the BitVector32 a cast is
required:

my_bitvector[(int)BitPos.Bit 1]; // get the value of the 1st bit

It appears that the generated byte code is identical - thus the explict cast
is not a performance hit.

Any thoughts would be appreciated!

BT
"Jesse McGrew" <jm*****@gmail. com> wrote in message
news:11******** *************@f 14g2000cwb.goog legroups.com...
Bit Twiddler wrote:
I went with the static readonly field method (Jesse, they can't be simple
variables because their values must *not* change after they are
initialized).


As Jon mentioned, you seem to have misunderstood me. I'm suggesting
something like this:

// declare an enum to hold the bit values
// the Flags attribute indicates that multiple values can be combined
[Flags]
enum BitPos {
None = 0,
Bit1 = 1,
Bit2 = 2,
Bit3 = 4,
// etc.
}

public void BitFieldDemo() {
// here is your bitfield
BitPos my_bits = BitPos.None;

// now let's set a bit
my_bits |= BitPos.Bit1;

// let's see if another bit is set
if ((my_bits & BitPos.Bit2) != 0)
Console.WriteLi ne("bit 2 is set - how did that happen?");
else
Console.WriteLi ne("good, bit 2 is not set");
}

Now you won't have to cast when you set, unset, or test bits. You will
have to cast if you need to convert my_bits to/from an int, though. One
benefit of using a [Flags] enum is you can call my_bits.ToStrin g() to
get a human-readable string like "Bit1, Bit3" instead of just a number.

Jesse

Dec 24 '05 #7
I've never encountered the BitVector32 class before, but after skimming
the documentation for it, my suggestion is to ditch it and just store
your bits in a BitPos variable. BitVector32 doesn't really seem to do
much other than wrapping the &, |, and << operators, unless you're
using it in "section" mode.

Furthermore, since enums can be based on any integer type, they can
store 8, 16, 32, or 64 bits, while a BitVector32 is always 32 bits
wide. For example, to define an enum that can hold 64 bits, start the
definition with "enum BitPos : long" instead of just "enum BitPos".

If you need to use BitVector32, for example to hide the details of
bitwise operations from inexperienced programmers who might read your
code, then I'd suggest storing the masks in static readonly int fields.
I wouldn't use constants, because that seems like an unnecessary mixing
of the two worlds - if you're going to hardcode the masks yourself
(rather than using CreateMask), why not go all the way and do the
bitwise operations yourself too?

Jesse

Dec 26 '05 #8

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

Similar topics

13
9552
by: SpaceCowboy | last post by:
I recently got into a discussion with a co-worker about using enums across a dll interface. He wanted to use chars instead, argueing that depending on compiler settings the size of an enum could change and lead to memory corruption. I didn't see how this was possible. He claims that if a dll built for a program is built with different compiler settings than the launcher program, the enum size could change. The only way I could figure...
4
2273
by: David Rasmussen | last post by:
The problem comes up in all sorts of contexts. But here is an example: We want to model the basics of chess, maybe for making a chess program, or maybe just to make an interactive board or ... We have to have the notions of colors, squares and pieces represented. Ideally, we want to be able to do things like initializing the board: void initial() {
27
2735
by: Mark A. Gibbs | last post by:
i have been toying with the idea of making my enums smarter - ie, more in line with the rest of the language. i haven't tested it yet, but what i came up with is a template like this: template <typename Enum> class smart_enum { public: typedef Enum enum_type;
6
2051
by: Noah Roberts | last post by:
I am having an interesting compilation error that makes me wonder if enums can conflict with each other. For example: class A { enum X { TEST, TEST2 }; public: ....
4
2098
by: Craig | last post by:
Newbie... I'm casting enums back and forth to ints so to use them as an index into a complex two dimensional array. I thought it would help readability. Instead, my code has casts all over the place. All the casting is giving me the jitters. Where did I go wrong? Thanks!
4
5591
by: Martin Pritchard | last post by:
Hi, I'm working on a project that historically contains around 40 enums. In the database various fields refer to the int values of these enums, but of course ref integrity is not enofrced and when looking at the db we can't tell what the value in a field represents. The other problem is that our enums are currently all stored in a single class, which means that because of no visibility constraints the enums are often used out of context...
3
1659
by: lou zion | last post by:
hi all, i'm trying to use a classes enums in another class, but can't seem to find the right syntax. i've got class A which has: enum EditTypeA {Currency, Percent, LabeledNumber, Text}; EditTypeA LineType; // LineType holds widget type, and will be either Currency, Percent, LabeledNumber or Text
2
2882
by: Simon Elliott | last post by:
I have some legacy C++ code which requires some enums to be 1 or 2 bytes in size. I'd ideally like to be able to specify that a few carefully selected enums are a particular size. By default, g++ seems to create enums of 4 bytes in length, unless I use the -fshort-enums option. I don't much want to use this all or nothing approach in case it breaks library code etc, and there's no guarantee that other compilers have a comparable...
7
8942
by: Victor Eijkhout | last post by:
Intel icc seems to think that enums are not ints: #include <stdlib.h> typedef enum { TRUE=1, FALSE=0 } Truth; #undef __FUNCT__ #define __FUNCT__ "getcontrols" int getcontrols(Truth *screen) {
0
9456
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...
1
9246
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,...
1
6742
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
6035
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
4553
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4816
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3264
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
2733
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2182
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.