Matlabにはdec2bin
、10進数から2進数に変換する関数があります。したがって、たとえば、dec2bin(3)
を返し11
ます。
対応するbin2decもあります。これは、2進数の文字列を受け取り、10進数に変換するため、 。bin2dec('11')
を返し3
ます。
整数以外の10進数を2進数に変換する場合は、最初に、表現する最小の2進数を決定してから、前処理と後処理を少し組み合わせて実行します。 dec2binを使用して、探している結果を取得します。したがって、必要な最小の2進位が1/512位(または2 ^ -9)である場合、次のようにすることができます(binPrecisionは1/512に等しい)。
function result = myDec2Bin(decNum, binPrecision)
isNegative=(decNum < 0);
intPart=floor(abs(decNum));
binaryIntPart=dec2bin(intPart);
fracPart=abs(decNum)-intPart;
scaledFracPart=round(fracPart / binPrecision);
scaledBinRep=dec2bin(scaledFracPart);
temp=num2str(10^log2(1/binPrecision)+str2num(scaledBinRep),'%d');
result=[binaryIntPart,'.',temp(2:end)];
if isNegative
result=['-',result];
end
end
その場合、の結果はにmyDec2Bin(0.256, 1/512)
なり0.010000011
、の結果はにmyDec2Bin(-0.984, 1/512)
なります-0.111111000
。(出力は文字列であることに注意してください。)