Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: How to bit shift hexadecimal digits

Okay, I am working on a card playing program, and I am storing card values as hexadecimal digits. Here is the array:

 public int[] originalCards = new int[54]
        {
            0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D,
            0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D,
            0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D,
            0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D,
            0x50, 0x51
        };

The first digit refers to the suit (1 = spades; 2 = clubs; .... 5 = Jokers) The second digit is the number of the card (1 = ace, 5 = 5; 13 = K, etc).

I would like to do something like the following:

Pseudocode:

    public int ReturnCard(int num)
    {
        int card = currentDeck[num];
        int suit = card.firsthexdigit;
        int value = card.secondhexdigit;
        return 0;
    }

I don't need a new method to work on ints, I just included it for clarity's sake.

Anybody know how to do this in C#?

Edit: Okay, I am using bit shifting as described in one of the answers. I can get the second digit (the suit) just fine, but the first digit keeps coming out as '0'. Any idea why?

Edit:edit: okay, works fine now. Thanks guys.

like image 359
Biosci3c Avatar asked Dec 09 '22 17:12

Biosci3c


2 Answers

You're not really "parsing" as such, just doing some simple bit manipulation.

int card = currentDeck[num];
int suit = (card & 0xF0) >> 4;
int value = card & 0x0F;

Will do what you want.

like image 73
Dean Harding Avatar answered Dec 24 '22 23:12

Dean Harding


To answer your question about the use of 0xF0 and 0x0F in the bit shift example what they are doing is a bitwise AND. When you do card & 0xF0 what you are doing is anding the two values, this results in setting all bits except the 4 you are interested in to 0. Ex:

 0x48   01001000     0x48   01001000
&0x0F  &00001111    &0xF0  &11110000
-----   --------     ----   --------
 0x08   00001000     0x48   01000000 >> 4
                            --------
                            00000100
like image 37
Robert Menteer Avatar answered Dec 24 '22 23:12

Robert Menteer