Tuesday 27 December 2016

Floating Point Number Into Binary Options

En un sistema de procesamiento de datos que tiene una pluralidad de unidades de almacenamiento, conteniendo cada unidad en un formato de punto flotante entero o normalizado, un bit de signo de exponente, un campo de exponente, un bit de signo de número entero / de fracción, Y un campo entero / de fracción, un convertidor transforma los datos almacenados en valores binarios puros de selectivamente el mismo o el orden relativo inverso. Para convertir en el mismo orden relativo, el bit de signo de exponente se complementa si el bit de signo entero / fracción es un cero lógico y el exponente se complementa si no es así. A continuación, se complementa el bit de número entero / fracción. Para convertir en el orden relativo inverso, el bit de signo exponente se complementa si el bit de signo entero / fracción es lógico y el campo exponente se complementa si no es así. Además, se complementa el campo entero / fracción. 1. Un convertidor para uso en un elemento lógico que almacena un valor digital numérico que tiene un bit de signo de exponente, un campo exponencial, un bit de signo entero / fracción y un campo entero / fraccionado, comprendiendo dicho convertidor : Medios de control que tienen un primer y un segundo estado lógico para controlar la conversión de dichos medios numéricos de valor digital para complementar dicho bit de signo exponencial cuando ambos bits de signo entero / fracción son iguales a ceros lógicos y dichos medios controladores están en dicho primer estado lógico y cuando Tanto dicho bit de signo entero / fracción es igual a uno lógico y dicho medio controlador está en dicho segundo medio de estado lógico para complementar dicho campo exponencial cuando tanto dicho bit de signo entero / fracción es igual a uno lógico y dichos medios controlador están en dicho primer estado lógico y Cuando dicho bit de signo entero / fracción es igual a cero lógico y dicho medio controlador está en dicho segundo estado lógico medios para complementar dicho campo entero / fracción cuando dichos medios controlador están en dicho segundo estado lógico y medios para complementar dicho bit entero / fracción cuando Dichos medios de control están en dicho primer estado lógico. 2. Un convertidor para uso en un elemento lógico que almacena un valor numérico digital que tiene un bit de signo de exponente y un campo exponente, un bit de signo entero / fracción y un campo entero / fracción, comprendiendo dicho convertidor: medios O exclusivos que tienen una salida Para combinar en modo O exclusivo el bit de signo de exponente con el complemento del bit de signo de número entero / fracción y para la combinación de iguales cada bit individual del campo de exponente con el bit de signo entero / fracción y para emitir todos los resultados de dichos medios de control de combinación que tienen un Un primer y un segundo estado lógico para controlar la conversión de dichos medios de complementación de valor digital numérico acoplados a la salida de dichos medios O exclusivos, el bit de signo entero / fracción y el campo entero / fracción, controlando dichos medios complementarios por dichos medios de control para Complementando cada bit recibido cuando dichos medios de control están en su primer estado lógico y para pasar incompletos cada bit recibido cuando dichos medios de control están en su segundo estado lógico. 3. Un convertidor para uso en un elemento lógico que almacena un valor numérico digital que tiene un bit de signo de exponente, un campo exponencial, un bit de signo entero / fracción y un campo entero / fracción, comprendiendo dicho convertidor: medios de control que tienen un primer y un segundo Segundo estado lógico para controlar la conversión de dicho valor digital variable un primer circuito O exclusivo alimentado por dichos medios de control y por el bit de signo entero / fracción un segundo circuito O exclusivo alimentado por dicho primer circuito OR exclusivo y por cada bit del campo exponente por el cual Cada bit en el campo del exponente se combina de forma exclusiva OU con la salida de dicho primer circuito O exclusivo, un circuito inversor que complementa la salida de dicho primer circuito O exclusivo, un tercer circuito O exclusivo alimentado por el bit del signo exponente y por la salida de dicho circuito Circuito inversor y medios de complementación que reciben el bit de signo entero / fracción y cada bit en el campo entero / fracción, siendo dichos medios de complementación controlados por dichos medios de control para complementar cada bit recibido cuando dichos medios de complementación están en su primer estado lógico y para pasar uncomplemented Recibiendo cada bit cuando dicho medio de control está en su segundo estado lógico. Esta es una división de la aplicación Ser. Nº 605.251, presentada el 18 de agosto de 1975, ahora Pat. 4.007.439. Antecedentes de la invención A medida que aumentan los requisitos de velocidad de los sistemas informáticos, se han desarrollado sistemas que emplean un mayor número de procesadores paralelos. Un sistema de este tipo, tiene en el orden de 64 procesadores paralelos, véase Pat. N ◦ 3.537.074, concedida el 27 de octubre de 1970 a R. A. Stokes y otros, y asignada al cesionario de la presente invención. Los sistemas informáticos grandes actuales que incorporan un alto grado de paralelismo incluyen a menudo una pluralidad de registros ampliamente dispersos. Cuando se comparan los datos de estos registros, los retardos de propagación implicados en la transmisión de datos de cada registro a un comparador central y de nuevo consumen un tiempo de procesamiento precioso y limitan el rendimiento global del sistema. Ciertos cálculos en grandes sistemas informáticos paralelos requieren la determinación de qué registro (s) en una pluralidad de registros dispersados ​​están almacenando los datos numéricos de valor más alto o más bajo. Cuando tales datos numéricos se almacenan en formato de punto flotante o entero, la determinación de qué registro almacena el valor de datos más alto o más bajo requiere una comparación de datos en serie compleja o que consume mucho tiempo. La conversión de todos los datos en equivalentes binarios facilita enormemente la tarea de comparación, pero dicha comparación es en sí misma relativamente compleja y costosa en términos de hardware o firmware. Se consigue una gran simplificación en la tarea de determinación global simplemente convirtiendo los datos almacenados en una representación binaria que mantiene el mismo orden de magnitud relativa de los datos almacenados originales pero no necesariamente los equivalentes binarios exactos de los mismos. Por lo tanto, un objeto de la presente invención es proporcionar un convertidor para transformar una pluralidad de valores de punto flotante o enteros en valores binarios de selectivamente el orden de magnitud inversa o igual. Es un objeto adicional de la presente invención proporcionar un convertidor de este tipo capaz de implementarse con componentes relativamente baratos combinados para funcionar de una manera eficiente de alta velocidad. Sumario de la invención Los anteriores y otros objetos de la invención se realizan mediante la conversión de datos de punto flotante o enteros almacenados en datos binarios que tienen selectivamente el orden de magnitud relativa inversa o igual. Los datos enteros o de punto flotante almacenados incluyen un bit de signo de exponente, un campo de exponente, un bit de signo entero / fracción y un campo entero / de fracción. Para convertir en el mismo orden relativo, el bit de signo exponente se complementa si el bit de signo entero / fracción es un cero lógico y el campo exponente se complementa si lo contrario. Además, se complementa el bit entero / fracción. Para convertir en el orden relativo inverso relativo, el bit del signo del exponente se complementa si el signo del entero / de la fracción es uno lógico y el campo del exponente se complementa si de otra manera. Además, se complementa el campo entero / fracción.- La configuración del sistema y los detalles operativos dados arriba han sido presentados en forma simplificada. Otras características de la invención se harán más evidentes en los dibujos y en la descripción detallada que se presentan a continuación. BREVE DESCRIPCIÓN DE LOS DIBUJOS La FIG. La figura 1 es un diagrama de bloques funcional que muestra las características de la presente invención. La figura 2A presenta el formato entero utilizado en la realización preferida de la invención. La figura 2B presenta el formato de coma flotante utilizado en la realización preferida de la invención. 2C es una tabla que demuestra el formato numérico normalizado de dos complementos utilizado en la invención. 3 es un diagrama lógico de un comparador mostrado en la FIG. 1 La FIG. 4 es un diagrama lógico alternativo para el comparador de la FIG. 3 La FIG. 5 es una tabla de verdad para un circuito decodificador mostrado en la Fig. 1 La FIG. 6 es una tabla de verdad para un circuito de comparación mostrado en la FIG. 1. DESCRIPCIÓN DETALLADA DE LA INVENCIÓN El método y aparato de conversión de punto entero y flotante de la presente invención reside en un entorno de procesamiento paralelo grande que tiene una pluralidad de elementos de procesamiento, véase la FIG. 1. Cada elemento 11 incluye un registro A 13 para almacenar datos numéricos en formatos de punto flotante o entero normalizados. De forma ocasional, el A registra 13 almacenar datos numéricos temporalmente antes, durante o después del procesamiento, es decir, multiplicación, división, adición, sustracción, etc. De vez en cuando, se hace necesario comparar datos en todos los registros A 13 para determinar qué registro (s) 13 almacena los datos numéricos de valor más alto o más bajo. De acuerdo con la presente invención, el proceso de determinación implica dos etapas básicas en las que los datos numéricos en cada registro A 13 se convierten primero en un patrón binario puro y después se buscan todos los patrones binarios dos bits a la vez para determinar cuál binario Patrón (s) tiene selectivamente el valor relativo más alto o más bajo. Cada registro A 13 almacena dos números complementarios de datos numéricos que pueden estar en cualquiera de los números enteros, véase la FIG. 2A, o punto flotante normalizado, véase la FIG. 2B, formato. Tanto en formato de punto entero como de punto flotante, un primer bit 15, denominado en lo sucesivo bit de signo de exponente 15, funciona como el bit más significativo cuando se ve el formato como un número binario puro. El bit de signo de exponente 15 se ajusta siempre a un cero lógico en el formato entero y significa el signo del exponente en formato de punto flotante con un cero lógico que significa un exponente positivo y un lógico que significa un exponente negativo. Inmediatamente después del signo del exponente el bit 15 en ambos formatos de punto entero y flotante es un primer campo de bits denominado en lo sucesivo campo exponente 17. En el formato de número entero todos los bits en el campo exponente 17 se ponen a cero lógico. En el formato de punto flotante, el campo exponente 17 representa el valor del exponente, véase la FIG. 2C. El campo exponente 17 puede comprender tres bits como se muestra en la FIG. 2C o más si es necesario para el rango de cálculo numérico de una aplicación específica o un sistema informático. Se ha encontrado que un campo exponente 17 que comprende siete bits es satisfactorio para una amplia gama de aplicaciones. Después del exponente el campo 17 es el bit 19 de signo entero / fracción que representa el signo entero en formato de enteros y el signo de fracciones en formato de coma flotante. Un bit de signo entero / fracción de cero lógico 19 significa un número entero positivo o una fracción mientras que un bit de signo entero / fraccionario lógico 1 19 significa un número entero o una fracción negativa. Un segundo campo de bits 21 a continuación denominado campo entero / fracción 21 sigue el bit de signo entero / fracción 19. El campo entero / fracción 21 representa el valor entero en formato entero y el valor de fracción en formato de punto flotante. El campo 21 de enteros / fracciones puede comprender tres bits como se muestra en la FIG. 2C o más si es necesario para el rango de cálculo numérico de una aplicación específica o un sistema informático. Se ha encontrado que un campo entero / fracción 21 que comprende 23 bits es satisfactorio para una amplia gama de aplicaciones. El punto binario 23 se considera que está siguiendo el campo entero / fracción 21 en formato de número entero y que precede al campo entero / de fracción 21 en formato de punto flotante. Como se ilustra en la FIG. 2C, la porción de fracción del formato de punto flotante se normaliza. Por lo tanto, 0001 que representa un valor positivo de 1/8 no es válido. Si se permitiera 1/8, las representaciones de ocho bits 0010 0001 y 0000 0100 tendrían ambos el valor de 1/2. Para asegurar solamente una representación para cada valor numérico, la fracción se normaliza como se muestra en la FIG. 2C prohibiendo (o declarando inválidas) fracciones que tengan su bit más significativo el mismo valor lógico que el bit de signo entero / fracción 19. Asimismo, para asegurar una única representación para el valor numérico cero, el punto flotante cero se define como el número que tiene Su bit de signo de exponente 15 en el lógico y todos los demás bits en el cero lógico. Con referencia de nuevo a la Fig. 1, se aprecia que las representaciones de punto flotante o entero discutidas anteriormente se almacenan temporalmente en una pluralidad de registros A 13 durante el curso normal de los cálculos informáticos. No importa si los datos numéricos se procesan en serie o en paralelo dentro y fuera de los registros A 13. Es importante que en un período de tiempo dado en los cálculos una pluralidad de registros A 13 almacenen datos enteros o de punto flotante y Que se desea determinar cuál (es) registro (s) A 13 almacena los datos de valor más alto o más bajo. Dicha determinación comienza con la conversión de datos. Los datos numéricos en cada registro A 13 se alimentan en paralelo a través de un convertidor asociado 25 a un registro B asociado 27 que sirve para almacenar los datos numéricos convertidos. Cada convertidor 25 funciona bajo el control de una unidad de control de selección alta / baja seleccionada 29 que genera un lógico o un cero lógico dependiendo de si se desea buscar el registro A 13 que almacena los datos numéricos más bajos o más altos. La conversión difiere para una búsqueda de registro alta y una búsqueda de registro bajo. Para seleccionar el registro (s) A 13 que almacena el valor más alto de datos numéricos se siguen cuatro pasos de conversión. En primer lugar, el bit de signo de exponente 15 se complementa si el bit de signo entero / fracción 19 es un cero lógico. En segundo lugar, el campo exponente 17 se complementa si el bit de signo entero / fracción 19 es lógico. En tercer lugar, el campo entero / fracción 21 permanece sin cambios. Finalmente, se complementa el bit de signo entero / fracción 19. Para seleccionar el registro (s) A 13 que almacena el valor más bajo de valor numérico se sigue otro conjunto de cuatro pasos de conversión. En primer lugar, el bit de signo de exponente 15 se complementa si el bit de signo entero / fracción 19 está en un lógico. En segundo lugar, el campo de exponentes 17 se complementa si el bit de signo entero / fracción 19 está en un cero lógico. En tercer lugar, el campo entero / fracción 21 se complementa. Finalmente, el bit de signo entero / fracción 19 permanece sin cambios. Las funciones del convertidor 25 se llevan a cabo usando herrajes estándar disponibles, véase la FIG. 3. Todos los bits del campo entero / fracción 21 y el bit de signo de número entero / fracción 19 se alimentan desde el registro A 13 a un circuito 31 de complemento de enteros / fracciones controlado por la unidad de control bajo selección / selección alta 29. Un cero lógico de La unidad 29 de control de alta / baja selección alta a la entrada de control 33 del circuito 31 de complemento de número entero / fracción permitirá que todos los bits pasen a través del mismo sin cambios al campo 37 de enteros / A la inversa, una unidad lógica de la unidad de control de selección alta / baja selectiva 29 hará que todos los bits sean complementados antes de pasar al registro B 27. La función simple del circuito de complemento de enteros / fracciones 31 puede realizarse físicamente en muchos Diferentes maneras bien conocidas por los expertos en la técnica de diseño lógico. Como ejemplo, muchos agregadores disponibles hoy en día también realizan la resta complementando una entrada. Por lo tanto, si una entrada se mantiene en cero lógico, la otra puede ser añadida a ella o efectivamente pasada a través del sumador sin cambios. Del mismo modo, con una entrada a cero, la función de sustracción servirá para complementar la otra entrada. En un modelo de trabajo de la invención, se ha fabricado un circuito 31 de complemento de enteros / fracciones satisfactorio utilizando el generador de función / unidad de lógica aritmética MC10181 disponible como un elemento estándar de Motorola, Inc. El MC10181 es sólo una unidad de cuatro bits y, por lo tanto, De dos o más se requiere para manejar campos enteros / de fracciones 21 que contienen más de tres bits. La salida de bits de signo entero / fracción convertida 36 del circuito de complemento de enteros / fracciones 31 es invertida lógicamente por un inversor lógico estándar 38 para producir una salida de inversor 39 que es el complemento del bit de signo entero / fracción 19 cuando el campo entero / fracción 21 no se complementa y que es lógicamente igual al bit de signo entero / fracción 19 de lo contrario. El bit de signo exponente 15 del registro A 13 se aplica a una primera entrada 41 de un circuito OR exclusivo 43. La segunda entrada 45 del circuito OR exclusivo 43 es alimentada a la salida de un inversor 47 que complementa el signo de número entero / fracción El bit 19 almacenado en un registro 13. La salida 49 del circuito OR exclusivo 43 se alimenta a través de un circuito complementario exponente 51 y se emite desde el mismo en la línea 53 de datos y se almacena como el bit 55 del signo exponente convertido en el registro B 27. El exponente El circuito de complemento 51 funciona bajo el control del circuito de control de selección alta / baja selección 29 para pasar los bits a través de la misma sin cambios o para complementarlos. Como tal, el circuito de complemento de exponente 51 es idéntico al circuito de complemento de enteros / fracción 31 y puede realizarse físicamente como se ha descrito anteriormente. El circuito de complemento exponente 51 sirve también para controlar el complemento del campo exponente 17 almacenado en un registro A 13. A este fin, todos los bits del campo exponente 17 son alimentados a través de la ruta de datos 56 a un sistema exclusivo O 57. Otra entrada 59 es Proporcionada al sistema OR exclusivo 57 a partir del bit de signo entero / fracción 19 almacenado en un registro 13. El sistema exclusivo O 57 funciona como una pluralidad de circuitos OR exclusivos, uno para cada bit en el campo exponente 17 y puede ser fabricado como un Pluralidad de circuitos OR exclusivos estándar. La salida 60 del sistema OR exclusivo 57 se alimenta a través del circuito complementario de exponente 51 al campo exponente convertido 61 del registro B 27. Como se ha indicado, el circuito de control bajo selecto alto / selecto 29 sirve meramente para generar una lógica o una lógica Cero dependiendo de si se desea una búsqueda del (de los) registro (s) alto (s) o registro (s) bajo. Como tal, el circuito de control 29 no representa más que una salida de flip-flop cuyas entradas son generadas por lógica de decisión dentro del entorno de ordenador en el que se realiza la presente invención. HIGO. 4 representa una aproximación alternativa a la realización del convertidor 25. En comparación con la realización del convertidor 25 de la Fig. 3, se ve que las porciones de número entero / fracción permanecen iguales y que las diferencias implican la sustitución de un circuito OR exclusivo 63 para el circuito complementario exponente 51 y el ligero recambio necesario por la sustitución. El OR exclusivo 63 es introducido por el bit de signo de número entero / fracción 19 y el circuito de control de selección de alta / baja selección 29. El circuito exclusivo de OR 63 acciona el inversor 47 y el sistema exclusivo de OR 57. La salida 60 del sistema exclusivo de OR 57 Proporciona directamente el campo del exponente convertido 61. Después de la conversión, comienza el proceso de búsqueda del registro alto o bajo, véase nuevamente la FIG. Como se describirá con mayor detalle a continuación, los datos convertidos en el registro B 27 se desplazan dos bits a la vez en un primer y segundo circuito de selección de entrada 67 y 69, respectivamente. Generalmente, los circuitos de entrada 67 y 69 simplemente pasan bits del registro B 27 al flip-flop 71 de D y al flip-flop 73 de E, respectivamente. Sin embargo, como se discutirá más adelante, en el primer paso de un ciclo de búsqueda, dos bits se pasan desde el convertidor 25, un bit al flip-flop 71 y el otro bit al flip-flop 73. La salida D 75 del flip-flop D 71 y la salida E del flip-flop E 73 se introducen en un circuito de decodificación 79 que tiene una salida A 81, una salida B 83 y una salida C 85. La FIG. La figura 5 ilustra de manera de tabla la función del circuito de decodificación 79. Puede observarse que el circuito de decodificación 79 proporciona básicamente una conversión binaria a 1-en-3. La salida A 81 del circuito de descodificación 79 alimenta un circuito OR 87. Como se muestra, el circuito OR 87 es alimentado por todas las salidas A 81, una para cada elemento 11 implicado en la búsqueda de registro alto / bajo. La salida del circuito OR 87 se alimenta como la entrada X 89 de un circuito de comparación 91. Como se muestra, hay un circuito de comparación 91 para cada elemento 11 implicado en la búsqueda. Del mismo modo, la salida B del circuito de descodificación 79 alimenta un circuito OR 93. La salida del circuito OR 93 se alimenta como la entrada Y 95 del circuito de comparación 91. Finalmente, la salida C 85 del circuito de decodificación 79 alimenta un circuito OR 97 La salida del circuito OR 97 se alimenta como la entrada Z 99 del circuito de comparación 91. La función del circuito de comparación 91 se ilustra en forma de tabla de verdad en la Fig. 6. Como se muestra, el circuito de comparación 91 emite un cero lógico en una línea de reposición 101 (véase la figura 1) cuando la salida D asociada 75 y la salida E 77 representan un número binario igual o mayor que cualquier otra salida D 75 y E Salida 77 generada por los otros elementos 11 implicados en la búsqueda de registro alto / bajo. Un lógico en la línea de reposición 101 restablece un flip-flop activo del elemento 103 que a su vez genera un nivel lógico en la línea 105, que como se detallará más adelante, elimina efectivamente el elemento asociado 11 de la búsqueda alta / baja. El procedimiento anterior de examinar los datos en los registros B 27 dos bits a la vez se continúa bajo el control de la unidad de control de cambio 107. La unidad de control de desplazamiento 107 desplaza bits del registro B 27 dos bits a la vez desde el más significativo al Bits menos significativos. El procedimiento de cambio se continúa hasta que todos los bits han sido desplazados fuera del registro B 27 y han sido procesados ​​a través del circuito de decodificación 79, los circuitos OR 87, 93 y 97 y el circuito de comparación 91. Después de que todos los bits han sido desplazados a través del circuito B 27 sólo los elementos 11 que tienen registros A 13 que almacenan selectivamente los datos de valor más alto o más bajo permanecen activos como se indica por el flip-flop de actividad de elemento 103. El procedimiento de búsqueda puede concluirse tempranamente si sólo queda un flip-flop de actividad de elemento 103 Activo en cualquier momento durante la búsqueda. El monitoreo de actividad de elemento 109 supervisa todos los flip-flops de actividad de elemento 103 y genera una señal de parada de búsqueda temprana 111 cuando uno y solo un flip-flop de actividad de elemento permanecen activos. El monitor de actividad de elemento 109 puede fabricarse a partir de un contador que se reduce un conteo cada vez que el flip-flop de actividad de elemento 103 indica que su elemento asociado 11 ya no está activo y aumenta un recuento cada vez que un nuevo flip-flop de actividad de elemento 103 indica que Un elemento 11 se ha activado. Pueden utilizarse también métodos alternativos de realización física del monitor de actividad del elemento 109. Por ejemplo, el monitor de actividad del elemento 109 puede ser fabricado como un circuito OR exclusivo que funciona para generar la señal de búsqueda / detención temprana cuando un solo flip-flop de actividad de un elemento 103 permanece activo. El sistema de conversión binaria de números enteros y flotantes de la presente invención se ha descrito en una realización específica que implica la búsqueda de un registro de almacenamiento de datos elevado o de un registro de almacenamiento de datos bajo. Se apreciará que se pueden prever e implementar otras configuraciones y aplicaciones del sistema que no están fuera del alcance de esta invención. Además, aunque la presente invención se ha descrito con cierto grado de particularidad, debe entenderse que la presente descripción se ha hecho a modo de ejemplo y que los cambios en la combinación y disposición de partes evidentes para un experto en la técnica pueden Se puede recurrir a sin apartarse del alcance y el espíritu de la invención. Convertidor de punto decimal a flotante Acerca del convertidor de decimal a punto flotante Este es un convertidor decimal a binario de punto flotante. Convertirá un número decimal en su número de punto flotante binario IEEE 754 de precisión simple y precisión doble más cercano, utilizando el redondeo de redondeo medio-par (el modo de redondeo IEEE predeterminado). Se implementa con aritmética de precisión arbitraria, por lo que sus conversiones se redondean correctamente. Se convertirá los números normales y subnormales, y convertirá los números que se desbordan (al infinito) o subflujo (a cero). El número de punto flotante resultante se puede mostrar en diez formas: en decimal, en binario, en notación científica decimal normalizada, en notación científica binaria normalizada, como un decimal normalizado veces una potencia de dos, como un entero decimal veces una potencia de dos , Como un entero decimal veces una potencia de diez, como una constante de punto flotante hexadecimal, en binario bruto, y en hexadecimal bruto. Cada formulario representa el valor exacto del número de coma flotante. ¿Por qué usar este convertidor? Este convertidor le mostrará por qué los números de sus programas de computadora, como 0.1, no se comportan como usted espera. Dentro de la computadora, la mayoría de los números con un punto decimal sólo puede ser aproximado otro número, sólo un poco lejos de la que desea, debe estar en ella. Por ejemplo, en punto flotante de precisión simple, 0.1 se convierte en 0.100000001490116119384765625. Si su programa está imprimiendo 0.1, le está mintiendo si está imprimiendo 0.100000001, it8217s que todavía miente, pero por lo menos it8217s que le dice usted realmente don8217t tiene 0.1. Cómo utilizar esta entrada del convertidor Introduzca un número positivo o negativo, ya sea en la forma estándar (por ejemplo 134.45) o en el exponente (por ejemplo, 1.3445e2). Indique valores fraccionarios con un punto decimal (lsquo. rsquo) y no utilice comas. Esencialmente, puede introducir lo que un programa de computadora acepta como literal de punto flotante, excepto sin sufijo (como lsquofrsquo). Marque las casillas para la precisión IEEE que desea elegir Doble. Soltero . o ambos. (Double es el valor por defecto.) Double significa un significand de 53 bits (menos si subnormal) con un exponente de 11 bits Single significa un significand de 24 bits (menos si subnormal) con un exponente de 8 bits. Marque las casillas para cualquier formato de salida que desee, elija uno o todos los diez. (Decimal es el valor predeterminado.) Haga clic en lsquoConvertrsquo para convertir. Haga clic en lsquoClearrsquo para restablecer el formulario y comenzar de cero. Si desea convertir otro número, simplemente escriba sobre el número original y haga clic en lsquoConvertrsquo 8212 no es necesario hacer clic primero en lsquoClearrsquo. Salida Hay diez formas de salida para elegir: Decimal. Muestra el número de coma flotante en decimal. (Amplíe el cuadro de salida, si es necesario, para ver todos los dígitos.) Binario. Muestra el número de punto flotante en binario. (Ampliar el cuadro de salida, si es necesario, para ver todos los dígitos.) Normalizada decimal notación científica. Muestra el número de coma flotante en decimal, pero compactamente, usando la notación científica normalizada. (Ampliar cuadro de salida, si es necesario, para ver todos los dígitos.) Normalizado binario notación científica. Muestra el número de coma flotante en binario, pero de manera compacta, utilizando la notación científica binaria normalizada. Nota . Los números subnormales se muestran normalizados, con su exponente real. Tiempos decimales normalizados una potencia de dos. Muestra el número de coma flotante en una notación científica normalizada híbrida, como un número decimal normalizado veces una potencia de dos. Enteros decimales veces una potencia de dos. Muestra el número de coma flotante como un entero decimal veces una potencia de dos. (La representación binaria del entero decimal es el patrón de bits de la representación de coma flotante, menos ceros finales.) Esta forma es muy interesante para los exponentes negativos, ya que representa el número de coma flotante como una fracción diádica. Enteros decimales veces una potencia de diez. Muestra el número de coma flotante como un entero decimal veces una potencia de diez. Esta forma es muy interesante para los exponentes negativos, ya que representa el número de coma flotante como una fracción. (Ampliar cuadro de salida, si es necesario, para ver todos los dígitos.) Hexadecimal constante de punto flotante. Muestra el número de punto flotante como una constante hexadecimal de punto flotante. Nota . Hay muchas maneras de dar formato a las constantes hexadecimales de punto flotante, como verías si, por ejemplo, comparas la salida de los programas Java, Visual C, gcc C y Python. Las diferencias a través de varios idiomas son superficiales aunque 8212 ceros finales pueden o no pueden ser mostrados, los exponentes positivos pueden o no tener un signo más, etc. Este convertidor formatea las constantes sin ceros a la izquierda y sin signos más. Nota . Como muchos lenguajes de programación, este convertidor muestra números subnormales no normalizados, con sus exponentes establecidos en el exponente normal mínimo. Nota . El último dígito hexadecimal en una constante de punto flotante hexadecimal puede tener 0s binarios al final dentro de este doesn8217t implica necesariamente que esos bits existen en el formato IEEE seleccionado. Binario sin procesar. Muestra el número de coma flotante en su formato IEEE sin procesar (bit de signo seguido del campo exponente seguido del campo significand). Raw hexadecimal. Muestra el número de coma flotante en su formato IEEE crudo, equivalente al formato binario bruto, pero expresado de forma compacta en hexadecimal. (Vea aquí para más detalles sobre estos formularios de salida.) Hay dos indicadores de salida: Inexact. Si está marcada, esto muestra que la conversión fue inexacta, es decir, se tuvo que redondear a una aproximación del número de entrada. (La conversión es inexacta cuando la salida decimal no coincide con la entrada decimal, pero esto es una forma más rápida de decirlo.) Nota. Este convertidor señala el desbordamiento hacia el infinito y el subflujo a cero como inexacto. Subnormal. Si está marcada, esto muestra que el número era demasiado pequeño, y convertido con menos de precisión completa (la precisión real se muestra entre paréntesis). Implementación Yo escribí este convertidor desde cero 8212 no se basa en funciones de conversión nativa como strtod () o strtof () o printf (). Se basa en el gran algoritmo basado en enteros que describo en mi artículo ldquoCorrect Decimal To Floating-Point Using Big Integers rdquo. I8217ve lo implementó usando BCMath. Límites Por razones prácticas, he establecido un límite arbitrario (algo) en la longitud de la entrada decimal you8217ll obtener un mensaje de error si lo golpea. Esto filtrará las entradas que de otro modo se desbordarían hasta el infinito o se reducirían a cero, pero también evitarán que ingrese algunos casos de redondeo a mitad de camino. (Para el registro, sin embargo, este convertidor acepta todos los ejemplos difíciles que he discutido en mi sitio.) Para todas las entradas que se aceptan sin embargo, la salida es correcta (a pesar de los errores que escapan a mis extensas pruebas). Los seres humanos usan sistemas numéricos decimales (base 10) y duodécima (base 12) para contar y medir (probablemente porque tenemos 10 dedos y dos dedos grandes). Las computadoras usan el sistema numérico binario (base 2), ya que están hechas de componentes digitales binarios (conocidos como transistores) que funcionan en dos estados: encendido y apagado. En computación, también usamos sistemas de números hexadecimales (base 16) u octales (base 8), como una forma compacta para representar números binarios. Decimal (Base 10) Sistema de números El sistema de números decimales tiene diez símbolos: 0, 1, 2, 3, 4, 5, 6, 7, 8 y 9, llamados dígitos s. Utiliza la notación posicional. That is, the least-significant digit (right-most digit) is of the order of 100 (units or ones), the second right-most digit is of the order of 101 (tens), the third right-most digit is of the order of 102 (hundreds), and so on. For example, We shall denote a decimal number with an optional suffix D if ambiguity arises. Binary (Base 2) Number System Binary number system has two symbols: 0 and 1, called bits . It is also a positional notation . for example, We shall denote a binary number with a suffix B. Some programming languages denote binary numbers with prefix 0b (e. g. 0b1001000 ), or prefix b with the bits quoted (e. g. b10001111 ). A binary digit is called a bit . Eight bits is called a byte (why 8-bit unit Probably because 82 3 ). Hexadecimal (Base 16) Number System Hexadecimal number system uses 16 symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F, called hex digits . It is a positional notation . for example, We shall denote a hexadecimal number (in short, hex) with a suffix H. Some programming languages denote hex numbers with prefix 0x (e. g. 0x1A3C5F ), or prefix x with hex digit quoted (e. g. xC3A4D98B ). Each hexadecimal digit is also called a hex digit . Most programming languages accept lowercase a to f as well as uppercase A to F . Computers uses binary system in their internal operations, as they are built from binary digital electronic components. However, writing or reading a long sequence of binary bits is cumbersome and error-prone. Hexadecimal system is used as a compact form or shorthand for binary bits. Each hex digit is equivalent to 4 binary bits, i. e. shorthand for 4 bits, as follows: Replace each hex digit by the 4 equivalent bits, for examples, Conversion from Binary to Hexadecimal Starting from the right-most bit (least-significant bit), replace each group of 4 bits by the equivalent hex digit (pad the left-most bits with zero if necessary), for examples, It is important to note that hexadecimal number provides a compact form or shorthand for representing binary bits. Conversion from Base r to Decimal (Base 10) Given a n - digit base r number: dn-1 dn-2 dn-3. d3 d2 d1 d0 (base r), the decimal equivalent is given by: Conversion from Decimal (Base 10) to Base r Use repeated division/remainder. For example, The above procedure is actually applicable to conversion between any 2 base systems. For example, General Conversion between 2 Base Systems with Fractional Part Separate the integral and the fractional parts. For the integral part, divide by the target radix repeatably, and collect the ramainder in reverse order. For the fractional part, multiply the fractional part by the target radix repeatably, and collect the integral part in the same order. Exercises (Number Systems Conversion) Convert the following decimal numbers into binary and hexadecimal numbers: 108 4848 9000 Convert the following binary numbers into hexadecimal and decimal numbers: 1000011000 10000000 101010101010 Convert the following hexadecimal numbers into binary and decimal numbers: ABCDE 1234 80F Convert the following decimal numbers into binary equivalent: 19.25D 123.456D Answers: You could use the Windows Calculator ( calc. exe ) to carry out number system conversion, by setting it to the scientific mode. (Run quotcalcquot rArr Select quotViewquot menu rArr Choose quotProgrammerquot or quotScientificquot mode.) 1101100B. 1001011110000B. 10001100101000B. 6CH. 12F0H. 2328H . 218H. 80H. AAAH. 536D. 128D. 2730D . 10101011110011011110B. 1001000110100B. 100000001111B. 703710D. 4660D. 2063D . Computer Memory amp Data Representation Computer uses a fixed number of bits to represent a piece of data, which could be a number, a character, or others. A n - bit storage location can represent up to 2 n distinct entities. For example, a 3-bit memory location can hold one of these eight binary patterns: 000. 001. 010. 011. 100. 101. 110. or 111. Hence, it can represent at most 8 distinct entities. You could use them to represent numbers 0 to 7, numbers 8881 to 8888, characters A to H, or up to 8 kinds of fruits like apple, orange, banana or up to 8 kinds of animals like lion, tiger, etc. Integers, for example, can be represented in 8-bit, 16-bit, 32-bit or 64-bit. You, as the programmer, choose an appropriate bit-length for your integers. Your choice will impose constraint on the range of integers that can be represented. Besides the bit-length, an integer can be represented in various representation schemes, e. g. unsigned vs. signed integers. An 8-bit unsigned integer has a range of 0 to 255, while an 8-bit signed integer has a range of -128 to 127 - both representing 256 distinct numbers. It is important to note that a computer memory location merely stores a binary pattern . It is entirely up to you, as the programmer, to decide on how these patterns are to be interpreted . For example, the 8-bit binary pattern quot0100 0001Bquot can be interpreted as an unsigned integer 65. or an ASCII character A. or some secret information known only to you. In other words, you have to first decide how to represent a piece of data in a binary pattern before the binary patterns make sense. The interpretation of binary pattern is called data representation or encoding . Furthermore, it is important that the data representation schemes are agreed-upon by all the parties, i. e. industrial standards need to be formulated and straightly followed. Once you decided on the data representation scheme, certain constraints, in particular, the precision and range will be imposed. Hence, it is important to understand data representation to write correct and high-performance programs. Rosette Stone and the Decipherment of Egyptian Hieroglyphs Egyptian hieroglyphs (next-to-left) were used by the ancient Egyptians since 4000BC. Unfortunately, since 500AD, no one could longer read the ancient Egyptian hieroglyphs, until the re-discovery of the Rosette Stone in 1799 by Napoleons troop (during Napoleons Egyptian invasion) near the town of Rashid (Rosetta) in the Nile Delta. The Rosetta Stone (left) is inscribed with a decree in 196BC on behalf of King Ptolemy V. The decree appears in three scripts: the upper text is Ancient Egyptian hieroglyphs . the middle portion Demotic script, and the lowest Ancient Greek . Because it presents essentially the same text in all three scripts, and Ancient Greek could still be understood, it provided the key to the decipherment of the Egyptian hieroglyphs. The moral of the story is unless you know the encoding scheme, there is no way that you can decode the data. Reference and images: Wikipedia. Integer Representation Integers are whole numbers or fixed-point numbers with the radix point fixed after the least-significant bit. They are contrast to real numbers or floating-point numbers . where the position of the radix point varies. It is important to take note that integers and floating-point numbers are treated differently in computers. They have different representation and are processed differently (e. g. floating-point numbers are processed in a so-called floating-point processor). Floating-point numbers will be discussed later. Computers use a fixed number of bits to represent an integer. The commonly-used bit-lengths for integers are 8-bit, 16-bit, 32-bit or 64-bit. Besides bit-lengths, there are two representation schemes for integers: Unsigned Integers . can represent zero and positive integers. Signed Integers . can represent zero, positive and negative integers. Three representation schemes had been proposed for signed integers: Sign-Magnitude representation 1s Complement representation 2s Complement representation You, as the programmer, need to decide on the bit-length and representation scheme for your integers, depending on your applications requirements. Suppose that you need a counter for counting a small quantity from 0 up to 200, you might choose the 8-bit unsigned integer scheme as there is no negative numbers involved. n - bit Unsigned Integers Unsigned integers can represent zero and positive integers, but not negative integers. The value of an unsigned integer is interpreted as quot the magnitude of its underlying binary pattern quot. Example 1: Suppose that n 8 and the binary pattern is 0100 0001B. the value of this unsigned integer is 1times20 1times26 65D . Example 2: Suppose that n 16 and the binary pattern is 0001 0000 0000 1000B. the value of this unsigned integer is 1times23 1times212 4104D . Example 3: Suppose that n 16 and the binary pattern is 0000 0000 0000 0000B. the value of this unsigned integer is 0 . An n - bit pattern can represent 2 n distinct integers. An n - bit unsigned integer can represent integers from 0 to (2 n )-1. as tabulated below: Signed Integers Signed integers can represent zero, positive integers, as well as negative integers. Three representation schemes are available for signed integers: Sign-Magnitude representation 1s Complement representation 2s Complement representation In all the above three schemes, the most-significant bit (msb) is called the sign bit . The sign bit is used to represent the sign of the integer - with 0 for positive integers and 1 for negative integers. The magnitude of the integer, however, is interpreted differently in different schemes. n - bit Sign Integers in Sign-Magnitude Representation In sign-magnitude representation: The most-significant bit (msb) is the sign bit . with value of 0 representing positive integer and 1 representing negative integer. The remaining n -1 bits represents the magnitude (absolute value) of the integer. The absolute value of the integer is interpreted as quotthe magnitude of the ( n -1)-bit binary patternquot. Example 1. Suppose that n 8 and the binary representation is 0 100 0001B . Sign bit is 0 rArr positive Absolute value is 100 0001B 65D Hence, the integer is 65D Example 2. Suppose that n 8 and the binary representation is 1 000 0001B . Sign bit is 1 rArr negative Absolute value is 000 0001B 1D Hence, the integer is -1D Example 3. Suppose that n 8 and the binary representation is 0 000 0000B . Sign bit is 0 rArr positive Absolute value is 000 0000B 0D Hence, the integer is 0D Example 4. Suppose that n 8 and the binary representation is 1 000 0000B . Sign bit is 1 rArr negative Absolute value is 000 0000B 0D Hence, the integer is -0D The drawbacks of sign-magnitude representation are: There are two representations ( 0000 0000B and 1000 0000B ) for the number zero, which could lead to inefficiency and confusion. Positive and negative integers need to be processed separately. n - bit Sign Integers in 1s Complement Representation In 1s complement representation: Again, the most significant bit (msb) is the sign bit . with value of 0 representing positive integers and 1 representing negative integers. The remaining n -1 bits represents the magnitude of the integer, as follows: for positive integers, the absolute value of the integer is equal to quotthe magnitude of the ( n -1)-bit binary patternquot. for negative integers, the absolute value of the integer is equal to quotthe magnitude of the complement ( inverse ) of the ( n -1)-bit binary patternquot (hence called 1s complement). Example 1. Suppose that n 8 and the binary representation 0 100 0001B . Sign bit is 0 rArr positive Absolute value is 100 0001B 65D Hence, the integer is 65D Example 2. Suppose that n 8 and the binary representation 1 000 0001B . Sign bit is 1 rArr negative Absolute value is the complement of 000 0001B. i. e. 111 1110B 126D Hence, the integer is -126D Example 3. Suppose that n 8 and the binary representation 0 000 0000B . Sign bit is 0 rArr positive Absolute value is 000 0000B 0D Hence, the integer is 0D Example 4. Suppose that n 8 and the binary representation 1 111 1111B . Sign bit is 1 rArr negative Absolute value is the complement of 111 1111B. i. e. 000 0000B 0D Hence, the integer is -0D Again, the drawbacks are: There are two representations ( 0000 0000B and 1111 1111B ) for zero. The positive integers and negative integers need to be processed separately. n - bit Sign Integers in 2s Complement Representation In 2s complement representation: Again, the most significant bit (msb) is the sign bit . with value of 0 representing positive integers and 1 representing negative integers. The remaining n -1 bits represents the magnitude of the integer, as follows: for positive integers, the absolute value of the integer is equal to quotthe magnitude of the ( n -1)-bit binary patternquot. for negative integers, the absolute value of the integer is equal to quotthe magnitude of the complement of the ( n -1)-bit binary pattern plus one quot (hence called 2s complement). Example 1. Suppose that n 8 and the binary representation 0 100 0001B . Sign bit is 0 rArr positive Absolute value is 100 0001B 65D Hence, the integer is 65D Example 2. Suppose that n 8 and the binary representation 1 000 0001B . Sign bit is 1 rArr negative Absolute value is the complement of 000 0001B plus 1. i. e. 111 1110B 1B 127D Hence, the integer is -127D Example 3. Suppose that n 8 and the binary representation 0 000 0000B . Sign bit is 0 rArr positive Absolute value is 000 0000B 0D Hence, the integer is 0D Example 4. Suppose that n 8 and the binary representation 1 111 1111B . Sign bit is 1 rArr negative Absolute value is the complement of 111 1111B plus 1. i. e. 000 0000B 1B 1D Hence, the integer is -1D Computers use 2s Complement Representation for Signed Integers We have discussed three representations for signed integers: signed-magnitude, 1s complement and 2s complement. Computers use 2s complement in representing signed integers. This is because: There is only one representation for the number zero in 2s complement, instead of two representations in sign-magnitude and 1s complement. Positive and negative integers can be treated together in addition and subtraction. Subtraction can be carried out using the quotaddition logicquot. Example 1: Addition of Two Positive Integers: Suppose that n8, 65D 5D 70D Example 2: Subtraction is treated as Addition of a Positive and a Negative Integers: Suppose that n8, 5D - 5D 65D (-5D) 60D Example 3: Addition of Two Negative Integers: Suppose that n8, -65D - 5D (-65D) (-5D) -70D Because of the fixed precision (i. e. fixed number of bits ), an n - bit 2s complement signed integer has a certain range. For example, for n 8. the range of 2s complement signed integers is -128 to 127. During addition (and subtraction), it is important to check whether the result exceeds this range, in other words, whether overflow or underflow has occurred. Example 4: Overflow: Suppose that n8, 127D 2D 129D (overflow - beyond the range) Example 5: Underflow: Suppose that n8, -125D - 5D -130D (underflow - below the range) The following diagram explains how the 2s complement works. By re-arranging the number line, values from -128 to 127 are represented contiguously by ignoring the carry bit. Range of n - bit 2s Complement Signed Integers An n - bit 2s complement signed integer can represent integers from -2( n -1) to 2( n -1)-1. as tabulated. Take note that the scheme can represent all the integers within the range, without any gap. In other words, there is no missing integers within the supported range. (263)-1 (9,223,372,036,854,775,807)(18 digits) Decoding 2s Complement Numbers Check the sign bit (denoted as S ). If S0. the number is positive and its absolute value is the binary value of the remaining n -1 bits. If S1. the number is negative. you could quotinvert the n -1 bits and plus 1quot to get the absolute value of negative number. Alternatively, you could scan the remaining n -1 bits from the right (least-significant bit). Look for the first occurrence of 1. Flip all the bits to the left of that first occurrence of 1. The flipped pattern gives the absolute value. For example, Big Endian vs. Little Endian Modern computers store one byte of data in each memory address or location, i. e. byte addressable memory. An 32-bit integer is, therefore, stored in 4 memory addresses. The termquotEndianquot refers to the order of storing bytes in computer memory. In quotBig Endianquot scheme, the most significant byte is stored first in the lowest memory address (or big in first), while quotLittle Endianquot stores the least significant bytes in the lowest memory address. For example, the 32-bit integer 12345678H (2215053170 10 ) is stored as 12H 34H 56H 78H in big endian and 78H 56H 34H 12H in little endian. An 16-bit integer 00H 01H is interpreted as 0001H in big endian, and 0100H as little endian. Exercise (Integer Representation) What are the ranges of 8-bit, 16-bit, 32-bit and 64-bit integer, in quotunsignedquot and quotsignedquot representation Give the value of 88. 0. 1. 127. and 255 in 8-bit unsigned representation. Give the value of 88. -88. -1. 0. 1. -128. and 127 in 8-bit 2s complement signed representation. Give the value of 88. -88. -1. 0. 1. -127. and 127 in 8-bit sign-magnitude representation. Give the value of 88. -88. -1. 0. 1. -127 and 127 in 8-bit 1s complement representation. TODO more. Answers The range of unsigned n - bit integers is 0, 2n - 1. The range of n - bit 2s complement signed integer is -2(n-1), 2(n-1)-1 88 (0101 1000). 0 (0000 0000). 1 (0000 0001). 127 (0111 1111). 255 (1111 1111) . 88 (0101 1000). -88 (1010 1000). -1 (1111 1111). 0 (0000 0000). 1 (0000 0001). -128 (1000 0000). 127 (0111 1111) . 88 (0101 1000). -88 (1101 1000). -1 (1000 0001). 0 (0000 0000 or 1000 0000). 1 (0000 0001). -127 (1111 1111). 127 (0111 1111) . 88 (0101 1000). -88 (1010 0111). -1 (1111 1110). 0 (0000 0000 or 1111 1111). 1 (0000 0001). -127 (1000 0000). 127 (0111 1111) . Floating-Point Number Representation A floating-point number (or real number) can represent a very large ( 1.23times1088 ) or a very small ( 1.23times10-88 ) value. It could also represent very large negative number ( -1.23times1088 ) and very small negative number ( -1.23times1088 ), as well as zero, as illustrated: A floating-point number is typically expressed in the scientific notation, with a fraction ( F ), and an exponent ( E ) of a certain radix ( r ), in the form of FtimesrE. Decimal numbers use radix of 10 ( Ftimes10E ) while binary numbers use radix of 2 ( Ftimes2E ). Representation of floating point number is not unique. For example, the number 55.66 can be represented as 5.566times101. 0.5566times102. 0.05566times103. y así. The fractional part can be normalized . In the normalized form, there is only a single non-zero digit before the radix point. For example, decimal number 123.4567 can be normalized as 1.234567times102 binary number 1010.1011B can be normalized as 1.0101011Btimes23 . It is important to note that floating-point numbers suffer from loss of precision when represented with a fixed number of bits (e. g. 32-bit or 64-bit). This is because there are infinite number of real numbers (even within a small range of says 0.0 to 0.1). On the other hand, a n - bit binary pattern can represent a finite 2 n distinct numbers. Hence, not all the real numbers can be represented. The nearest approximation will be used instead, resulted in loss of accuracy. It is also important to note that floating number arithmetic is very much less efficient than integer arithmetic. It could be speed up with a so-called dedicated floating-point co-processor . Hence, use integers if your application does not require floating-point numbers. In computers, floating-point numbers are represented in scientific notation of fraction ( F ) and exponent ( E ) with a radix of 2, in the form of Ftimes2E. Both E and F can be positive as well as negative. Modern computers adopt IEEE 754 standard for representing floating-point numbers. There are two representation schemes: 32-bit single-precision and 64-bit double-precision. IEEE-754 32-bit Single-Precision Floating-Point Numbers In 32-bit single-precision floating-point representation: The most significant bit is the sign bit ( S ), with 0 for positive numbers and 1 for negative numbers. The following 8 bits represent exponent ( E ). The remaining 23 bits represents fraction ( F ). Normalized Form Lets illustrate with an example, suppose that the 32-bit pattern is 1 1000 0001 011 0000 0000 0000 0000 0000. with: S 1 E 1000 0001 F 011 0000 0000 0000 0000 0000 In the normalized form . the actual fraction is normalized with an implicit leading 1 in the form of 1.F. In this example, the actual fraction is 1.011 0000 0000 0000 0000 0000 1 12-2 12-3 1.375D . The sign bit represents the sign of the number, with S0 for positive and S1 for negative number. In this example with S1. this is a negative number, i. e. -1.375D . In normalized form, the actual exponent is E-127 (so-called excess-127 or bias-127). This is because we need to represent both positive and negative exponent. With an 8-bit E, ranging from 0 to 255, the excess-127 scheme could provide actual exponent of -127 to 128. In this example, E-127129-1272D . Hence, the number represented is -1.37522-5.5D . De-Normalized Form Normalized form has a serious problem, with an implicit leading 1 for the fraction, it cannot represent the number zero Convince yourself on this De-normalized form was devised to represent zero and other numbers. For E0. the numbers are in the de-normalized form. An implicit leading 0 (instead of 1) is used for the fraction and the actual exponent is always -126. Hence, the number zero can be represented with E0 and F0 (because 0.02-1260 ). We can also represent very small positive and negative numbers in de-normalized form with E0. For example, if S1. E0. and F011 0000 0000 0000 0000 0000. The actual fraction is 0.01112-212-30.375D. Since S1. it is a negative number. With E0. the actual exponent is -126. Hence the number is -0.3752-126 -4.4times10-39. which is an extremely small negative number (close to zero). Summary In summary, the value ( N ) is calculated as follows: For 1 le E le 254, N (-1)S times 1.F times 2(E-127). These numbers are in the so-called normalized form. The sign-bit represents the sign of the number. Fractional part ( 1.F ) are normalized with an implicit leading 1. The exponent is bias (or in excess) of 127. so as to represent both positive and negative exponent. The range of exponent is -126 to 127 . For E 0, N (-1)S times 0.F times 2(-126). These numbers are in the so-called denormalized form. The exponent of 2-126 evaluates to a very small number. Denormalized form is needed to represent zero (with F0 and E0 ). It can also represents very small positive and negative number close to zero. For E 255. it represents special values, such as plusmnINF (positive and negative infinity) and NaN (not a number). This is beyond the scope of this article. Example 1: Suppose that IEEE-754 32-bit floating-point representation pattern is 0 10000000 110 0000 0000 0000 0000 0000 . Example 2: Suppose that IEEE-754 32-bit floating-point representation pattern is 1 01111110 100 0000 0000 0000 0000 0000 . Example 3: Suppose that IEEE-754 32-bit floating-point representation pattern is 1 01111110 000 0000 0000 0000 0000 0001 . Example 4 (De-Normalized Form): Suppose that IEEE-754 32-bit floating-point representation pattern is 1 00000000 000 0000 0000 0000 0000 0001 . Exercises (Floating-point Numbers) Compute the largest and smallest positive numbers that can be represented in the 32-bit normalized form. Compute the largest and smallest negative numbers can be represented in the 32-bit normalized form. Repeat (1) for the 32-bit denormalized form. Repeat (2) for the 32-bit denormalized form. Hints: Largest positive number: S0. E1111 1110 (254). F111 1111 1111 1111 1111 1111 . Smallest positive number: S0. E0000 00001 (1). F000 0000 0000 0000 0000 0000 . Same as above, but S1 . Largest positive number: S0. E0. F111 1111 1111 1111 1111 1111 . Smallest positive number: S0. E0. F000 0000 0000 0000 0000 0001 . Same as above, but S1 . Notes For Java Users You can use JDK methods Float. intBitsToFloat(int bits) or Double. longBitsToDouble(long bits) to create a single-precision 32-bit float or double-precision 64-bit double with the specific bit patterns, and print their values. For examples, IEEE-754 64-bit Double-Precision Floating-Point Numbers The representation scheme for 64-bit double-precision is similar to the 32-bit single-precision: The most significant bit is the sign bit ( S ), with 0 for positive numbers and 1 for negative numbers. The following 11 bits represent exponent ( E ). The remaining 52 bits represents fraction ( F ). The value ( N ) is calculated as follows: Normalized form: For 1 le E le 2046, N (-1)S times 1.F times 2(E-1023) . Denormalized form: For E 0, N (-1)S times 0.F times 2(-1022). These are in the denormalized form. For E 2047. N represents special values, such as plusmnINF (infinity), NaN (not a number). More on Floating-Point Representation There are three parts in the floating-point representation: The sign bit ( S ) is self-explanatory (0 for positive numbers and 1 for negative numbers). For the exponent ( E ), a so-called bias (or excess ) is applied so as to represent both positive and negative exponent. The bias is set at half of the range. For single precision with an 8-bit exponent, the bias is 127 (or excess-127). For double precision with a 11-bit exponent, the bias is 1023 (or excess-1023). The fraction ( F ) (also called the mantissa or significand ) is composed of an implicit leading bit (before the radix point) and the fractional bits (after the radix point). The leading bit for normalized numbers is 1 while the leading bit for denormalized numbers is 0. Normalized Floating-Point Numbers In normalized form, the radix point is placed after the first non-zero digit, e, g. 9.8765D10-23D. 1.001011B211B. For binary number, the leading bit is always 1, and need not be represented explicitly - this saves 1 bit of storage. In IEEE 754s normalized form: For single-precision, 1 le E le 254 with excess of 127. Hence, the actual exponent is from -126 to 127. Negative exponents are used to represent small numbers (lt 1.0) while positive exponents are used to represent large numbers (gt 1.0). N (-1)S times 1.F times 2(E-127) For double-precision, 1 le E le 2046 with excess of 1023. The actual exponent is from -1022 to 1023. and N (-1)S times 1.F times 2(E-1023) Take note that n-bit pattern has a finite number of combinations ( 2n ), which could represent finite distinct numbers. It is not possible to represent the infinite numbers in the real axis (even a small range says 0.0 to 1.0 has infinite numbers). That is, not all floating-point numbers can be accurately represented. Instead, the closest approximation is used, which leads to loss of accuracy . The minimum and maximum normalized floating-point numbers are: 0000 0001H 0 00000000 00000000000000000000001B E 0, F 00000000000000000000001B D(min) 0.0. 1 times 2-126 1 times 2-23 times 2-126 2-149 (asymp1.4 times 10-45) 007F FFFFH 0 00000000 11111111111111111111111B E 0, F 11111111111111111111111B D(max) 0.1. 1 times 2-126 (1-2-23)times2-126 (asymp1.1754942 times 10-38) 0000 0000 0000 0001H D(min) 0.0. 1 times 2-1022 1 times 2-52 times 2-1022 2-1074 (asymp4.9 times 10-324) 001F FFFF FFFF FFFFH D(max) 0.1. 1 times 2-1022 (1-2-52)times2-1022 (asymp4.4501477170144023 times 10-308) Special Values Zero . Zero cannot be represented in the normalized form, and must be represented in denormalized form with E0 and F0. There are two representations for zero: 0 with S0 and -0 with S1 . Infinity . The value of infinity (e. g. 1/0 ) and - infinity (e. g. -1/0 ) are represented with an exponent of all 1s ( E 255 for single-precision and E 2047 for double-precision), F0. and S0 (for INF ) and S1 (for - INF ). Not a Number (NaN) . NaN denotes a value that cannot be represented as real number (e. g. 0/0 ). NaN is represented with Exponent of all 1s ( E 255 for single-precision and E 2047 for double-precision) and any non-zero fraction. Character Encoding In computer memory, character are quotencodedquot (or quotrepresentedquot) using a chosen quotcharacter encoding schemesquot (aka quotcharacter setquot, quotcharsetquot, quotcharacter mapquot, or quotcode pagequot). For example, in ASCII (as well as Latin1, Unicode, and many other character sets): code numbers 65D (41H) to 90D (5AH) represents A to Z. respectively. code numbers 97D (61H) to 122D (7AH) represents a to z. respectivamente. code numbers 48D (30H) to 57D (39H) represents 0 to 9. respectively. It is important to note that the representation scheme must be known before a binary pattern can be interpreted. P. ej. the 8-bit pattern quot 0100 0010B quot could represent anything under the sun known only to the person encoded it. The most commonly-used character encoding schemes are: 7-bit ASCII (ISO/IEC 646) and 8-bit Latin-x (ISO/IEC 8859-x) for western european characters, and Unicode (ISO/IEC 10646) for internationalization (i18n). A 7-bit encoding scheme (such as ASCII) can represent 128 characters and symbols. An 8-bit character encoding scheme (such as Latin-x) can represent 256 characters and symbols whereas a 16-bit encoding scheme (such as Unicode UCS-2) can represents 65,536 characters and symbols. 7-bit ASCII Code (aka US-ASCII, ISO/IEC 646, ITU-T T.50) ASCII (American Standard Code for Information Interchange) is one of the earlier character coding schemes. ASCII is originally a 7-bit code. It has been extended to 8-bit to better utilize the 8-bit computer memory organization. (The 8th-bit was originally used for parity check in the early computers.) Code numbers 32D (20H) to 126D (7EH) are printable (displayable) characters as tabulated: ISO/IEC-8859 has 16 parts. Besides the most commonly-used Part 1, Part 2 is meant for Central European (Polish, Czech, Hungarian, etc), Part 3 for South European (Turkish, etc), Part 4 for North European (Estonian, Latvian, etc), Part 5 for Cyrillic, Part 6 for Arabic, Part 7 for Greek, Part 8 for Hebrew, Part 9 for Turkish, Part 10 for Nordic, Part 11 for Thai, Part 12 was abandon, Part 13 for Baltic Rim, Part 14 for Celtic, Part 15 for French, Finnish, etc. Part 16 for South-Eastern European. Other 8-bit Extension of US-ASCII (ASCII Extensions) Beside the standardized ISO-8859-x, there are many 8-bit ASCII extensions, which are not compatible with each others. ANSI (American National Standards Institute) (aka Windows-1252 . or Windows Codepage 1252): for Latin alphabets used in the legacy DOS/Windows systems. It is a superset of ISO-8859-1 with code numbers 128 (80H) to 159 (9FH) assigned to displayable characters, such as quotsmartquot single-quotes and double-quotes. A common problem in web browsers is that all the quotes and apostrophes (produced by quotsmart quotesquot in some Microsoft software) were replaced with question marks or some strange symbols. It it because the document is labeled as ISO-8859-1 (instead of Windows-1252), where these code numbers are undefined. Most modern browsers and e-mail clients treat charset ISO-8859-1 as Windows-1252 in order to accommodate such mis-labeling. EBCDIC (Extended Binary Coded Decimal Interchange Code): Used in the early IBM computers. Unicode (aka ISO/IEC 10646 Universal Character Set) Before Unicode, no single character encoding scheme could represent characters in all languages. For example, western european uses several encoding schemes (in the ISO-8859-x family). Even a single language like Chinese has a few encoding schemes (GB2312/GBK, BIG5). Many encoding schemes are in conflict of each other, i. e. the same code number is assigned to different characters. Unicode aims to provide a standard character encoding scheme, which is universal, efficient, uniform and unambiguous. Unicode standard is maintained by a non-profit organization called the Unicode Consortium ( unicode. org ). Unicode is an ISO/IEC standard 10646. Unicode is backward compatible with the 7-bit US-ASCII and 8-bit Latin-1 (ISO-8859-1). That is, the first 128 characters are the same as US-ASCII and the first 256 characters are the same as Latin-1. Unicode originally uses 16 bits (called UCS-2 or Unicode Character Set - 2 byte), which can represent up to 65,536 characters. It has since been expanded to more than 16 bits, currently stands at 21 bits. The range of the legal codes in ISO/IEC 10646 is now from U0000H to U10FFFFH (21 bits or about 2 million characters), covering all current and ancient historical scripts. The original 16-bit range of U0000H to UFFFFH (65536 characters) is known as Basic Multilingual Plane (BMP), covering all the major languages in use currently. The characters outside BMP are called Supplementary Characters . which are not frequently-used. Unicode has two encoding schemes: UCS-2 (Universal Character Set - 2 Byte): Uses 2 bytes (16 bits), covering 65,536 characters in the BMP. BMP is sufficient for most of the applications. UCS-2 is now obsolete. UCS-4 (Universal Character Set - 4 Byte): Uses 4 bytes (32 bits), covering BMP and the supplementary characters. UTF-8 (Unicode Transformation Format - 8-bit) The 16/32-bit Unicode (UCS-2/4) is grossly inefficient if the document contains mainly ASCII characters, because each character occupies two bytes of storage. Variable-length encoding schemes, such as UTF-8, which uses 1-4 bytes to represent a character, was devised to improve the efficiency. In UTF-8, the 128 commonly-used US-ASCII characters use only 1 byte, but some less-commonly characters may require up to 4 bytes. Overall, the efficiency improved for document containing mainly US-ASCII texts. The transformation between Unicode and UTF-8 is as follows: 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx In UTF-8, Unicode numbers corresponding to the 7-bit ASCII characters are padded with a leading zero thus has the same value as ASCII. Hence, UTF-8 can be used with all software using ASCII. Unicode numbers of 128 and above, which are less frequently used, are encoded using more bytes (2-4 bytes). UTF-8 generally requires less storage and is compatible with ASCII. The drawback of UTF-8 is more processing power needed to unpack the code due to its variable length. UTF-8 is the most popular format for Unicode. UTF-8 uses 1-3 bytes for the characters in BMP (16-bit), and 4 bytes for supplementary characters outside BMP (21-bit). The 128 ASCII characters (basic Latin letters, digits, and punctuation signs) use one byte. Most European and Middle East characters use a 2-byte sequence, which includes extended Latin letters (with tilde, macron, acute, grave and other accents), Greek, Armenian, Hebrew, Arabic, and others. Chinese, Japanese and Korean (CJK) use three-byte sequences. All the bytes, except the 128 ASCII characters, have a leading 1 bit. In other words, the ASCII bytes, with a leading 0 bit, can be identified and decoded easily. Ejemplo. (Unicode: 60A8H 597DH) UTF-16 (Unicode Transformation Format - 16-bit) UTF-16 is a variable-length Unicode character encoding scheme, which uses 2 to 4 bytes. UTF-16 is not commonly used. The transformation table is as follows: Same as UCS-2 - no encoding 000uuuuu zzzzyyyy yyxxxxxx (uuuuune0) 110110ww wwzzzzyy 110111yy yyxxxxxx (wwww uuuuu - 1) Take note that for the 65536 characters in BMP, the UTF-16 is the same as UCS-2 (2 bytes). However, 4 bytes are used for the supplementary characters outside the BMP. For BMP characters, UTF-16 is the same as UCS-2. For supplementary characters, each character requires a pair 16-bit values, the first from the high-surrogates range, ( uD800-uDBFF ), the second from the low-surrogates range ( uDC00-uDFFF ). UTF-32 (Unicode Transformation Format - 32-bit) Same as UCS-4, which uses 4 bytes for each character - unencoded. Formats of Multi-Byte (e. g. Unicode) Text Files Endianess (or byte-order). For a multi-byte character, you need to take care of the order of the bytes in storage. In big endian . the most significant byte is stored at the memory location with the lowest address (big byte first). In little endian . the most significant byte is stored at the memory location with the highest address (little byte first). For example, (with Unicode number of 60A8H ) is stored as 60 A8 in big endian and stored as A8 60 in little endian. Big endian, which produces a more readable hex dump, is more commonly-used, and is often the default. BOM (Byte Order Mark). BOM is a special Unicode character having code number of FEFFH. which is used to differentiate big-endian and little-endian. For big-endian, BOM appears as FE FFH in the storage. For little-endian, BOM appears as FF FEH. Unicode reserves these two code numbers to prevent it from crashing with another character. Unicode text files could take on these formats: Big Endian: UCS-2BE, UTF-16BE, UTF-32BE. Little Endian: UCS-2LE, UTF-16LE, UTF-32LE. UTF-16 with BOM. The first character of the file is a BOM character, which specifies the endianess. For big-endian, BOM appears as FE FFH in the storage. For little-endian, BOM appears as FF FEH . UTF-8 file is always stored as big endian. BOM plays no part. However, in some systems (in particular Windows), a BOM is added as the first character in the UTF-8 file as the signature to identity the file as UTF-8 encoded. The BOM character ( FEFFH ) is encoded in UTF-8 as EF BB BF. Adding a BOM as the first character of the file is not recommended, as it may be incorrectly interpreted in other system. You can have a UTF-8 file without BOM. Formats of Text Files Line Delimiter or End-Of-Line (EOL). Sometimes, when you use the Windows NotePad to open a text file (created in Unix or Mac), all the lines are joined together. This is because different operating platforms use different character as the so-called line delimiter (or end-of-line or EOL). Two non-printable control characters are involved: 0AH (Line-Feed or LF) and 0DH (Carriage-Return or CR). Windows/DOS uses OD0AH (CRLF or quot rn quot) as EOL. Unix and Mac use 0AH (LF or quot n quot) only. End-of-File (EOF). TODO Windows CMD Codepage Character encoding scheme (charset) in Windows is called codepage . In CMD shell, you can issue command quotchcpquot to display the current codepage, or quotchcp codepage-numberquot to change the codepage. The default codepage 437 (used in the original DOS) is an 8-bit character set called Extended ASCII . which is different from Latin-1 for code numbers above 127. Codepage 1252 (Windows-1252), is not exactly the same as Latin-1. It assigns code number 80H to 9FH to letters and punctuation, such as smart single-quotes and double-quotes. A common problem in browser that display quotes and apostrophe in question marks or boxes is because the page is supposed to be Windows-1252, but mislabelled as ISO-8859-1. For internationalization and chinese character set: codepage 65001 for UTF8, codepage 1201 for UCS-2BE, codepage 1200 for UCS-2LE, codepage 936 for chinese characters in GB2312, codepage 950 for chinese characters in Big5. Chinese Character Sets Unicode supports all languages, including asian languages like Chinese (both simplified and traditional characters), Japanese and Korean (collectively called CJK). There are more than 20,000 CJK characters in Unicode. Unicode characters are often encoded in the UTF-8 scheme, which unfortunately, requires 3 bytes for each CJK character, instead of 2 bytes in the unencoded UCS-2 (UTF-16). Worse still, there are also various chinese character sets, which is not compatible with Unicode: GB2312/GBK: for simplified chinese characters. GB2312 uses 2 bytes for each chinese character. The most significant bit (MSB) of both bytes are set to 1 to co-exist with 7-bit ASCII with the MSB of 0. There are about 6700 characters. GBK is an extension of GB2312, which include more characters as well as traditional chinese characters. BIG5: for traditional chinese characters BIG5 also uses 2 bytes for each chinese character. The most significant bit of both bytes are also set to 1. BIG5 is not compatible with GBK, i. e. the same code number is assigned to different character. For example, the world is made more interesting with these many standards: Notes for Windows CMD Users. To display the chinese character correctly in CMD shell, you need to choose the correct codepage, e. g. 65001 for UTF8, 936 for GB2312/GBK, 950 for Big5, 1201 for UCS-2BE, 1200 for UCS-2LE, 437 for the original DOS. You can use command quot chcp quot to display the current code page and command quot chcp codepagenumber quot to change the codepage. You also have to choose a font that can display the characters (e. g. Courier New, Consolas or Lucida Console, NOT Raster font). Collating Sequences (for Ranking Characters) A string consists of a sequence of characters in upper or lower cases, e. g. quotapplequot. quotBOYquot. quotCatquot. In sorting or comparing strings, if we order the characters according to the underlying code numbers (e. g. US-ASCII) character-by-character, the order for the example would be quotBOYquot. quotapplequot. quotCatquot because uppercase letters have a smaller code number than lowercase letters. This does not agree with the so-called dictionary order . where the same uppercase and lowercase letters have the same rank. Another common problem in ordering strings is quot10quot (ten) at times is ordered in front of quot1quot to quot9quot . Hence, in sorting or comparison of strings, a so-called collating sequence (or collation ) is often defined, which specifies the ranks for letters (uppercase, lowercase), numbers, and special symbols. There are many collating sequences available. It is entirely up to you to choose a collating sequence to meet your applications specific requirements. Some case-insensitive dictionary-order collating sequences have the same rank for same uppercase and lowercase letters, i. e. A. a rArr B. b rArr. rArr Z. z. Some case-sensitive dictionary-order collating sequences put the uppercase letter before its lowercase counterpart, i. e. A rArr B rArr C. rArr a rArr b rArr c. Typically, space is ranked before digits 0 to 9. followed by the alphabets. Collating sequence is often language dependent, as different languages use different sets of characters (e. g. aacute, eacute, a, alpha) with their own orders. For Java Programmers - java. nio. Charset JDK 1.4 introduced a new java. nio. charset package to support encoding/decoding of characters from UCS-2 used internally in Java program to any supported charset used by external devices. Ejemplo. The following program encodes some Unicode texts in various encoding scheme, and display the Hex codes of the encoded byte sequences. For Java Programmers - char and String The char data type are based on the original 16-bit Unicode standard called UCS-2. The Unicode has since evolved to 21 bits, with code range of U0000 to U10FFFF. The set of characters from U0000 to UFFFF is known as the Basic Multilingual Plane ( BMP ). Characters above UFFFF are called supplementary characters. A 16-bit Java char cannot hold a supplementary character. Recall that in the UTF-16 encoding scheme, a BMP characters uses 2 bytes. It is the same as UCS-2. A supplementary character uses 4 bytes. and requires a pair of 16-bit values, the first from the high-surrogates range, ( uD800-uDBFF ), the second from the low-surrogates range ( uDC00-uDFFF ). In Java, a String is a sequences of Unicode characters. Java, in fact, uses UTF-16 for String and StringBuffer. For BMP characters, they are the same as UCS-2. For supplementary characters, each characters requires a pair of char values. Java methods that accept a 16-bit char value does not support supplementary characters. Methods that accept a 32-bit int value support all Unicode characters (in the lower 21 bits), including supplementary characters. This is meant to be an academic discussion. I have yet to encounter the use of supplementary characters Displaying Hex Values amp Hex Editors At times, you may need to display the hex values of a file, especially in dealing with Unicode characters. A Hex Editor is a handy tool that a good programmer should possess in his/her toolbox. There are many freeware/shareware Hex Editor available. Try google quotHex Editorquot. I used the followings: NotePad with Hex Editor Plug-in: Open-source and free. You can toggle between Hex view and Normal view by pushing the quotHquot button. PSPad: Freeware. You can toggle to Hex view by choosing quotViewquot menu and select quotHex Edit Modequot. TextPad: Shareware without expiration period. To view the Hex value, you need to quotopenquot the file by choosing the file format of quotbinaryquot (). UltraEdit: Shareware, not free, 30-day trial only. Let me know if you have a better choice, which is fast to launch, easy to use, can toggle between Hex and normal view, free. The following Java program can be used to display hex code for Java Primitives (integer, character and floating-point): In Eclipse, you can view the hex code for integer primitive Java variables in debug mode as follows: In debug perspective, quotVariablequot panel Select the quotmenuquot (inverted triangle) Java Java Preferences. Primitive Display Options Check quotDisplay hexadecimal values (byte, short, char, int, long)quot. Summary - Why Bother about Data Representation Integer number 1. floating-point number 1.0 character symbol 1. and string quot1quot are totally different inside the computer memory. You need to know the difference to write good and high-performance programs. In 8-bit signed integer . integer number 1 is represented as 00000001B . In 8-bit unsigned integer . integer number 1 is represented as 00000001B . In 16-bit signed integer . integer number 1 is represented as 00000000 00000001B . In 32-bit signed integer . integer number 1 is represented as 00000000 00000000 00000000 00000001B . In 32-bit floating-point representation . number 1.0 is represented as 0 01111111 0000000 00000000 00000000B. i. e. S0. E127. F0 . In 64-bit floating-point representation . number 1.0 is represented as 0 01111111111 0000 00000000 00000000 00000000 00000000 00000000 00000000B. i. e. S0. E1023. F0 . In 8-bit Latin-1, the character symbol 1 is represented as 00110001B (or 31H ). In 16-bit UCS-2, the character symbol 1 is represented as 00000000 00110001B . In UTF-8, the character symbol 1 is represented as 00110001B . If you quotaddquot a 16-bit signed integer 1 and Latin-1 character 1 or a string quot1quot, you could get a surprise. Exercises (Data Representation) For the following 16-bit codes: Give their values, if they are representing: a 16-bit unsigned integer a 16-bit signed integer two 8-bit unsigned integers two 8-bit signed integers a 16-bit Unicode characters two 8-bit ISO-8859-1 characters. Ans: (1) 42. 32810 (2) 42. -32726 (3) 0. 42 128. 42 (4) 0. 42 -128. 42 (5) (6) NUL. PAD. . REFERENCES amp RESOURCES (Floating-Point Number Specification) IEEE 754 (1985), quotIEEE Standard for Binary Floating-Point Arithmeticquot. (ASCII Specification) ISO/IEC 646 (1991) (or ITU-T T.50-1992), quotInformation technology - 7-bit coded character set for information interchangequot. (Latin-I Specification) ISO/IEC 8859-1, quotInformation technology - 8-bit single-byte coded graphic character sets - Part 1: Latin alphabet No. 1quot. (Unicode Specification) ISO/IEC 10646, quotInformation technology - Universal Multiple-Octet Coded Character Set (UCS)quot. Unicode Consortium unicode. org . Last modified: January, 2014


No comments:

Post a Comment