Results 1 to 5 of 5

Thread: [RESOLVED] Inverting Bits

  1. #1

    Thread Starter
    Member
    Join Date
    Sep 2010
    Posts
    43

    Resolved [RESOLVED] Inverting Bits

    Hi,

    I am trying to find a way to invert the lower 4 bits of a byte. For example, I need to convert:

    0x64 (0110 0100) to 0x6B (0110 1011)

    I can do it with what I think is an unreasonable amount of code. Lots of if statements and a loop.

    Is there an easier way using bitwise operators?

    Thanks

    Sonny

  2. #2
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    38,989

    Re: Inverting Bits

    You will need to mask off the high bits, first, if you don't want to change them:

    dim temp as Integer = (&HFF00 AND myByte)
    myByte = (myByte AND &HFF)

    Now you would have the high bits in temp, and myByte holds only the four bits that you care about. You could use a byte rather than an integer, but I don't think it makes much difference for this.

    The final step would be the inversion, though it could be built right into the other step, if you wanted to:

    myByte = NOT myByte

    There is a problem with that, though, because it will invert all 8 bits, so the high bits will be set to 1. One thing you could do then would be to mask out the high bits, again, but you already did that, so you might as well combine it into these two steps:

    dim temp As Byte= (myByte AND &HFF00)
    myByte = (((NOT myByte) AND &HFF) OR temp)
    My usual boring signature: Nothing

  3. #3
    Fanatic Member ThomasJohnsen's Avatar
    Join Date
    Jul 2010
    Location
    Denmark
    Posts
    528

    Re: Inverting Bits

    ...or if you find subtraction to be more intuitive than using not (though you did specify bitwise operators), you can try something like:
    Code:
    Dim result As Byte = Convert.ToByte((yourbyte And &HF0) + &HF - (yourbyte And &HF))
    In truth, a mature man who uses hair-oil, unless medicinally , that man has probably got a quoggy spot in him somewhere. As a general rule, he can't amount to much in his totality. (Melville: Moby Dick)

  4. #4
    Cumbrian Milk's Avatar
    Join Date
    Jan 2007
    Location
    0xDEADBEEF
    Posts
    2,448

    Re: Inverting Bits

    It should be just a case of using a bitwise Xor with the appropriate mask.
    I'm not too familiar with VB.Net syntax but based on ThomasJohnsen's post...
    Code:
    Dim result As Byte = Convert.ToByte(yourbyte Xor 15)
    W o t . S i g

  5. #5

    Thread Starter
    Member
    Join Date
    Sep 2010
    Posts
    43

    Re: [RESOLVED] Inverting Bits

    Thanks for the help. Those ideas worked.

    Sonny

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width