フィルターのクリア

Write Decimals to 12 Bit Signed Binary

23 ビュー (過去 30 日間)
Karl Haebler
Karl Haebler 2017 年 11 月 28 日
コメント済み: Walter Roberson 2017 年 11 月 29 日
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

採用された回答

Walter Roberson
Walter Roberson 2017 年 11 月 28 日
temp = integers;
mask = temp < 0;
temp(mask) = 2^12 + temp(mask) ;
binary = dec2bin(temp, 12);
  3 件のコメント
Karl Haebler
Karl Haebler 2017 年 11 月 29 日
Nevermind I figured it out! Thanks for the help
Walter Roberson
Walter Roberson 2017 年 11 月 29 日
temp = cellstr(binary);
fprintf(fileID, '%s\n', temp{:});

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSimulink についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by