Considering an array of integer numbers:
X = [1, 3, 3, 3,2,3 ,1,1,2,3]
I want to convert each number to its 4 bit binary equivalent. I have done the following, but the result is not correct. It seems that the MSB and LSB are reversed. I tried using MATLAB's function with decimal_to_bin =dec2bin(X) but even this output is wrong.
How can I fix this?
X = [1, 3, 3, 3,2,3 ,1,1,2,3];
b = 4;
lookup_table = generate_lookupTable(b);
BinaryX = lookup_table(X,:);
function result = generate_lookupTable(b)
% generate binary code
k = 2^b;
result = zeros(k,b);
for i=1:k
for j=1:b
result(i,j) = bitand(uint8(2^(j-1)),uint8(i-1))/uint8(2^(j-1));
end
end
end
The output that I got is BinaryX
0 0 0 0
0 1 0 0
0 1 0 0
0 1 0 0
1 0 0 0
0 1 0 0
0 0 0 0
0 0 0 0
1 0 0 0
0 1 0 0

I think beaker means something along these lines:
% Your vector
X = [1, 3, 3, 3,2,3 ,1,1,2,3];
% number of bits to use
numbits = 4;
% Create lookup table
little_endian = true;
LUT = dec2bin(0:15, numbits) == '1';
if ~little_endian
LUT = fliplr(LUT); end
% The conversion
bits = LUT(X(:) + 1, :)
Alternatively, you can do what dec2bin does, but without all the fuss around it:
bits = (rem(floor(X(:)*pow2(1-numbits:0)),2) == 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With