Struct help

Started by
4 comments, last by Alan Kemp 19 years, 5 months ago

#define empty 0x01
#define Player1 0x02
#define Player2 0x04
#define Padding 0x08

struct Locale
{
	unsigned EM : 1;
	unsigned P1 : 1;
	unsigned P2 : 1;
	unsigned PD : 1;
};

So, I want to be able to have like an 8x8 Locale. So i do... Locale *Board = new Locale[64]; Now, what do I need to do to make it so that I can just do: Board[x + y*8] = empty; Am I going about this all wrong? The idea is that I have a 4 bit Locale struct and if the first bit is set, then the spot is empty. If the second bit is set, then P1 has the spot, etc. Thanks for any help.
Advertisement
I'm not sure, but I don't think you can do it that way. You're trying to combine two approaches - an explicit bitfield using the : syntax, and an implicit bitfield using constants.

With your struct set up as it is, to make position x, y empty, you would say:

Board[x + y * 8].EM = 1;

Or, you could just make Board an array of unsigned something or another, and say:

Board[x + y * 8] = empty;

Assuming both players can occupy a single spot, you could say:

Board[...] |= Player1;
Board[...] |= Player2;

If a spot can only have a single state, there's really no point in using the 0x constants - just use enumerated constants and assign those.

'Hope some of that was helpful...
Thanks. I think I got it figured out. :)
I would implement this as a 'normal' bitfield. So:

const int empty = 0x1;const int Player1 = 0x2;const int Player2 = 0x4;unsigned int * Board = new unsigned int[64];


Now just use bitwise and (&) to determine if certain bits are set. Use normal = to set the status.

Board[x + y*8] = empty; // now emptyBoard[x + y*8] = Player1; // occupied by player 1if (Board[x + y*8] & empty){    // This square is empty}if (Board[x + y*8] & Player1){    // This square is occupied by player 1}


You can find loads of information for bit manipulation on google if you want to read more.

Alan

/Edit: Made a stuid mistake defining constants. Thanks Zahlman.

[Edited by - Alan Kemp on November 24, 2004 4:13:11 PM]
"There will come a time when you believe everything is finished. That will be the beginning." -Louis L'Amour
Quote:Original post by Alan Kemp
I would implement this as a 'normal' bitfield. So:


const int empty = 0x1;const int Player1 = 0x2;const int Player2 = 0x3; // <--- uh...// const int empty = 1 << 0;// const int Player1 = 1 << 1;// const int Player2 = 1 << 2;
Quote:Original post by Zahlman
Quote:Original post by Alan Kemp
I would implement this as a 'normal' bitfield. So:


*** Source Snippet Removed ***


Erg, indeed. I was so busy changing define's to const int's I made an even worse mistake.

Alan
"There will come a time when you believe everything is finished. That will be the beginning." -Louis L'Amour

This topic is closed to new replies.

Advertisement