Write Decimals to 12 Bit Signed Binary

23 visualizaciones (últimos 30 días)
Karl Haebler
Karl Haebler el 28 de Nov. de 2017
Comentada: Walter Roberson el 29 de Nov. de 2017
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

Respuesta aceptada

Walter Roberson
Walter Roberson el 28 de Nov. de 2017
temp = integers;
mask = temp < 0;
temp(mask) = 2^12 + temp(mask) ;
binary = dec2bin(temp, 12);
  3 comentarios
Karl Haebler
Karl Haebler el 29 de Nov. de 2017
Nevermind I figured it out! Thanks for the help
Walter Roberson
Walter Roberson el 29 de Nov. de 2017
temp = cellstr(binary);
fprintf(fileID, '%s\n', temp{:});

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by