Changing the bits randomly
2 views (last 30 days)
Show older comments
I have a binary value
10000100000 which is 1056
i am changing last 5 bits
10000111111 which is 1087
now keeping last 5 bits constant i have to change other bits to get closer value of 1056
for ex i have changed one bit from 1 to 0
10000011111 which is 1055..like this i have to check,please tell how to process in a loop and check all bits ,manually i checked ,but i need in a for loop,or using GA
PLEASE HELP
0 Comments
Answers (3)
Jan
on 9 Nov 2012
x = 1087;
for bit = 6:16
orig = bitget(x, bit);
new = bitset(x, bit, 1-orig);
if new < x
x = new;
end
end
C.J. Harris
on 9 Nov 2012
Try this, it is a somewhat brute force approach to solving your problem. The value 'nMatch' should give you the desired answer:
nInput = 1056;
A = dec2bin(nInput);
A(end-4:end) = '1';
nRest = 2^length(A(1:end-5)) - 1;
nCombs = dec2bin(0:nRest);
maxErr = Inf;
for nCount = 1:nRest
testVal = bin2dec([nCombs(nCount,:) A(end-4:end)]);
if abs(nInput - testVal) < maxErr
maxErr = abs(nInput - testVal);
nMatch = testVal;
end
end
0 Comments
C.J. Harris
on 9 Nov 2012
or less brute force without a for loop:
nInput = 1056;
nShift = bin2dec('11111');
nOffset = nInput - nShift;
nNear = round(nOffset/(nShift + 1));
nMatch = nNear*(nShift + 1) + nShift;
See Also
Categories
Find more on Whos 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!