Write Decimals to 12 Bit Signed Binary

조회 수: 28 (최근 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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by