Change Bit Value for Some positions

21 views (last 30 days)
Albert Sagala
Albert Sagala on 5 Dec 2017
Commented: Roger Stafford on 6 Dec 2017
In binary number. Example 8 bit resolution in the measurement 10001111. In case I have many measurement data with 8 bits. And I want to change the bit value in the 4th bit only. If it is 0 then changes to 1, if it 1 then changes to 0.
so values 11101001 will become 11111001 and value 11100000 will become 11110000
I have a lof data, I can do changes in the 8th bits using command DEC2BIN(BIN2DEC(F4)+DEC2BIN(1)). I am still looking for the other positions.
Kind regards

Answers (2)

Roger Stafford
Roger Stafford on 6 Dec 2017
Use the 'xor' function. If one of the arguments is of type uint8 with a single bit equal to 1 and the rest 0, the corresponding bit in the other uint8 argument will be reversed.

Albert Sagala
Albert Sagala on 6 Dec 2017
Edited: Albert Sagala on 6 Dec 2017
xor(11110000,00010000)
ans =
0
I want the ans 11100000
  1 Comment
Roger Stafford
Roger Stafford on 6 Dec 2017
My apologies! I should have said, "Use the bitxor function." (The 'xor' function handles logical trues and falses in a manner similar to & and | operations.) The 'bitxor' function deals with the individual bits in a number. However, writing bitxor(11110000,00010000) will undoubtedly interpret those as decimal, not binary, numbers.
Confession: At the moment I forget how one would enter binary numbers. In your example (out of desperation) I would write bitxor(15*16,16) where 15*16 in binary is 11110000 and 16 in binary is 00010000, which should give as a result 224, which has one bit reversed - that is, decimal 224 = binary 11100000.

Sign in to comment.

Categories

Find more on File Operations in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!