Pregunta: | 7541 - CONVERTIR FLOAT DEL FORMATO DEC AL FORMATO STANDARD DE IEEE |
Autor: | Laura |
Tengo un problemilla con un programa en Visual C++.
Necesito convertir un float (o double) del formato DEC (Single Precision Floating point Format), al formato standard (IEEE) pq sino voy a tener problemas con el compilador. Conoces alguna funcion q haga este tipo de conversion,pero sin cambiar el tipo de variable. O sino me puedes dar un pista de como lo podria resolver (esq desplazando los bits es un lio q no veas...) |
Respuesta: | Gustavo |
El formato IEEE 754, que creo es el que vos nocesitas; para single precision utiliza 32 bits, el bit mas significativo es de signo,
despues 8 bits para codificar el exponente, y los ultimos 23 bits para la mantisa. La formula que se utiliza para obtener el numero flotante es (-1)**s * (1+mantiza)*2**(exp - 127.) En este sitio podes encontrar la informacion necesaria. http://www.public.iastate.edu/~selavi/guide/ieee754/ie3.html Si te sirve de algo este codigo que lo hice con un amigo para un trabajo, convierte de float a formato IEEE (Hexadecimal), pero lo devuelve en un string. Espero esto te sirva de algo. #include <iostream.h> #include <conio.h> #include <math.h> #include <string.h> void float2ieee754_32(float valor, char hexa[10]); void main (void) { char hexa[10]; float f=0; while (f!=(-1)) { cin >> f; float2ieee754_32(f,hexa); cout << "\nvalor: " << hexa; } };/ void float2ieee754_32(float valor, char hexa[10]) { int frontera=127; int bits[32]; bits[0]=(valor < 0); int e=0; float temp=fabs(valor); while (temp < 1) { temp=temp * 2; e--; }; while (temp > 2) { temp=temp / 2; e++; }; e=frontera+e; bits[1]=(128 & e)==128; bits[2]=(64 & e)==64; bits[3]=(32 & e)==32; bits[4]=(16 & e)==16; bits[5]=(8 & e)==8; bits[6]=(4 & e)==4; bits[7]=(2 & e)==2; bits[8]=(1 & e)==1; temp=temp - 1; float k=0.5; int ok; for (int i=9; i < 32; i++) { ok=0; if (k <= temp) { temp=temp-k; ok=1; } k=k/2; bits[i]=ok; }; int j=0; int xxx=0; char hexatable[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; strcpy(hexa,"0"); for (i=0; i < 32;i++, j++) { if (!(3-j == 0 && bits[i]==0)) xxx=xxx + pow(2*bits[i],3-j); if (j == 3) { char xx[2]; xx[0]=hexatable[xxx]; xx[1]=0; strcat(hexa,xx); xxx=0; j=(-1); } }; strcat(hexa,"h"); }; Gustavo |