Write Decimals to 12 Bit Signed Binary
23 次查看(过去 30 天)
显示 更早的评论
I am trying to take a set of integer decimal inputs (ranging from -100 to 100) and map them to 12 bit signed binary. The trick is that the binary must consists of 12 bits, even if there are leading zeros. So far I have generated the integers, converted them to 16 (not 12) bit signed binary, but am really struggling with making all of the binary numbers 12 bits long.
For example, if the integer is 23, the binary should be 000000010111. If the integer is -23, the binary should be 111111101001. I then need to write these signed binary numbers to a text file with each binary number on a new line. So far I have what is below, but the output is 16 bit and there are no leading zeros. I have struggled for an answer but haven't found it. Any help is greatly appreciated!
integers=round(200*(rand(1,8000)-0.5));
for i=1:8000
binary{i}=dec2bin(typecast(int16(integers(i)),'uint16'));
end
0 个评论
采纳的回答
Walter Roberson
2017-11-28
temp = integers;
mask = temp < 0;
temp(mask) = 2^12 + temp(mask) ;
binary = dec2bin(temp, 12);
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!