MATLAB: How to convert integer to 12 bit binary and vise versa

binary to decimaldecimal to binarymatlab function

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.

Best 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.