How to convert integer to 12 bit binary and vise versa

Hello, I want to convert integers in the range -400 to +800 to 12 bit binary and vice versa.
dec= -333;
a= decimalToBinaryVector(typecast(int16(dec),'uint16'),16);
str_x = num2str(a);
b=typecast(uint16(bin2dec(str_x)),'int16')
The above code gives me 16 bit Binary value. I want to convert the integer to 12 bit binary and vice versa.

2 Comments

Why? Your code at https://www.mathworks.com/matlabcentral/answers/508682-how-to-pass-binary-values-to-mex already does 12 bit conversion.
Yes Walter, the code does 12 bit conversion. It works well with positive integers, but with negative numbers, I get wrong results while converting from binary to decimal.
b=-70.199;
Y = round(b,1);
dec= Y*10;
temp = dec;
mask = temp < 0;
temp(mask) = 2^12 + temp(mask) ; %temp = 3394
a=decimalToBinaryVector(temp, 12); %a= [1 1 0 1 0 1 0 0 0 0 1 0]
% binary to decimal
str_x = num2str(a);
b=typecast(uint16(bin2dec(str_x)),'int16') % b = 3394
The output of b must be -70.199 but I get 3394 as the decimal value.

Sign in to comment.

 Accepted Answer

mod(typecast(int16(dec), 'uint16'), 4096)
and convert to binary.
Or
bitget(int16(dec), 12:-1:1)
which does the binary conversion. You might want to double() the output for your purposes.

4 Comments

Walter, the decimal to binary conversion works well, but I am not getting correct value of the decimal number .
b=-70.199;
Y = round(b,1);
dec= Y*10;
a1=mod(typecast(int16(dec), 'uint16'), 4096) %a1 = 3394
a=decimalToBinaryVector(a1); %a1= [1 1 0 1 0 1 0 0 0 0 1 0]
% binary to decimal
str_x = num2str(a);
b1=typecast(uint16(bin2dec(str_x)),'int16') % b = 3394
The output of b1 is 3394 but the correct output is -70.199
b=-70.199;
Y = round(b,1);
dec= Y*10;
a= decimalToBinaryVector(typecast(int16(dec),'uint16'),16);
str_x = num2str(a);
b=typecast(uint16(bin2dec(str_x)),'int16');
The above code does the correct conversion to decimal number. But the decimal to binary value is in 16bit, I want that in 12bits
b = int16(sum(bitset(0,12:-1:1,a)));
if b > 2047; b = b - 4096; end
Hi Walter, your code is the perfect fit to my problem. Thanks a lot.

Sign in to comment.

More Answers (1)

There's no int12 data type in MATLAB. Depending on what you want to do with this data, if you have Fixed-Point Designer you could store it as an fi object. See this documentation page for the basics of how to work with fi objects.
>> A = sfi(10, 12, 0)
A =
10
DataTypeMode: Fixed-point: binary point scaling
Signedness: Signed
WordLength: 12
FractionLength: 0
>> bin(A)
ans =
'000000001010'

1 Comment

Hello Steven, Thanks a lot for your response. Gonna learn something new today, about Fixed point designer. Will look into the documentation page and how it fits my project and will update you..Thanks again.

Sign in to comment.

Asked:

A R
on 5 Mar 2020

Commented:

A R
on 6 Mar 2020

Community Treasure Hunt

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

Start Hunting!