Extracting representative bits for an integer and doing the reverse.
Show older comments
I have an integer value and want to extract all its representative bits in two-bit blocks; each block consists of two bits. Reversely, I want to build an integer value from given two-bit blocks. What is the more optimized code performing these tasks?
Accepted Answer
More Answers (1)
Image Analyst
on 18 Nov 2012
Edited: Image Analyst
on 18 Nov 2012
% Say, for 171 = AB = 10101011.
str = dec2bin(171)
theBlocks = reshape(str, [2 4])'
In the command window:
str =
10101011
theBlocks =
10
10
10
11
To reconstruct from theBlocks:
reconstructedString = reshape(theBlocks', [1 8])
reconstructedInteger = bin2dec(reconstructedString)
In the command window:
reconstructedString =
10101011
reconstructedInteger =
171
Is that what you mean?
8 Comments
Digitalsd
on 19 Nov 2012
Walter Roberson
on 19 Nov 2012
subtract '0' (the string which is the character for the digit 0) to convert to integer type.
Multiply the first of each pair by 2 and add the second of each pair, to get 0, 1, 2, or 3.
Jan
on 19 Nov 2012
Please post example data in Matlab syntax. "Blocks" and "string type", "integer type", "0,1,2,3 values" and "reverse" is not exactly clear, such that an answer needs too much guessing.
Walter Roberson
on 19 Nov 2012
Any integer? What about negative integers?
Image Analyst
on 19 Nov 2012
How about smallNumber = mod(yourBigNumber, 3). That will give 0-3 for any integer. I totally agree with Jan that you're not being clear about what you want, hence my answer now being totally different than what I first gave. Why don't you give a question that can be answered the very first time without us guessing and trying numerous times to help you?
Walter Roberson
on 19 Nov 2012
I'm pretty sure that the poster is trying to do base 4 encoding / decoding.
Digitalsd
on 19 Nov 2012
Categories
Find more on Logical 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!