473,789 Members | 2,617 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 1548
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
9558
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
2277
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
2747
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
2053
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
2103
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
5593
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
1661
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
2884
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
8943
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
9666
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10199
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
10139
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
9983
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
9020
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
5551
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4092
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
3700
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2909
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.