Changing the bits randomly
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(3 个)
Jan
2012-11-9
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
2012-11-9
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 个评论
C.J. Harris
2012-11-9
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;
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!