-
Dec 15th, 2012, 02:30 PM
#1
Thread Starter
Member
[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
-
Dec 15th, 2012, 03:01 PM
#2
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
-
Dec 16th, 2012, 08:09 AM
#3
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)
-
Dec 16th, 2012, 09:28 AM
#4
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)
-
Dec 16th, 2012, 01:09 PM
#5
Thread Starter
Member
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|