0

Basically, I've been searching for days now how to work with bits and bitmasks and learned some pretty interesting stuff, mainly about how computers work. The question is a result of me trying to work with the Minecraft protocol. Part of that is bitmasks on a byte. Through my searching I think I've got this concept down, but I'm not entirely sure. I wasn't sure how to test my work either, because I haven't found a way to represent the byte as a string (maybe I'm just slow and forgetful).

Simply put, here is my code for setting a bit based on a bit mask. Had I done this correctly?

    // BitMask is based on Enum byte value (0x00, 0x01, 0x02, 0x04, 0x08, etc.)
    public void SetBitOn(Enum value, bool on)
    {
        // Ignore this part, just part of the software I'm working on
        // to determine what type is being worked on
        if (Type != EntityMetadataType.Byte)
            throw new ArgumentException("Type must be of byte");

        byte mask = Convert.ToByte(value);
        byte val = (byte) Value;
        if (on)
        {
            val &= (byte) ~mask;
        }
        else
        {
            val |= (byte) mask;
        }

        Value = val;
    }
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
apotter96
  • 156
  • 12
  • You seem to have forgotten to ask a question. – ikegami Nov 26 '19 at 20:49
  • 2
    You mixed up the on and off branch – Holger Nov 26 '19 at 20:50
  • @Holger so with that corrected, is this right? Did I do it correctly? – apotter96 Nov 26 '19 at 20:52
  • 1
    Yes, and to check yourself maybe read this: https://stackoverflow.com/questions/47904471/visual-studio-debugger-displaying-integer-values-in-binary – Holger Nov 26 '19 at 21:02
  • 1
    Dont edit your original question with the answer. Makes it completely useless for anyone googling this problem in the future. If you want to do that post it as an answer. Please edit it back and post the corrected version as an answer. – DetectivePikachu Nov 26 '19 at 21:13
  • 1
    I've rolled back your last edit, to preserve the original question. As noted above, you should _not_ edit faulty code in the question to correct errors that are specifically related to the question, as it negates the value of the question. Beyond that, please read [ask] and [mcve], so you understand better how to present a useful question on Stack Overflow, in a clear, answerable way. It is important to be _specific_, provide concise, complete code, and state clearly what your _one_ question is. ... – Peter Duniho Nov 26 '19 at 21:55
  • 1
    ... Note that "is this code okay?" is not a real question. "My code does this, I'd rather it does that, I tried this but it didn't work, what should I do instead?" is a real question. – Peter Duniho Nov 26 '19 at 21:55

0 Answers0