Guest User

binToFloat function

a guest
Aug 24th, 2013
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.41 KB | None | 0 0
  1. /*
  2. Autor: Fernando Mendonça de Almeida
  3.  
  4. Descriçao: Função para transformar um número binário com ou sem ponto flutuante em um número decimal com ponto flutuante
  5.  
  6. Utilização:
  7.     binToFloat("1") // 1.0f
  8.     binToFloat("10") // 2.0f
  9.     binToFloat("10.1") // 2.5f
  10.     binToFloat("111.01") // 7.25f
  11.     binToFloat("9991119999.99999099991") // 7.25f (Números fora do escopo do binário com ponto flutuante são ignorados)
  12.     binToFloat("9991119999.99999099991", 0) // 7.25f (Números fora do escopo do binário com ponto flutuante são ignorados)
  13.     binToFloat("9991119999.99999099991", 1) // -1.0f (Números fora do escopo do binário com ponto flutuante são verificados e caso existam, é retornado -1)
  14.  
  15. */
  16.  
  17. float binToFloat(const char* str, const int tratarRuido){
  18.     int tmpInt = 0;
  19.     int tmpCount = 0;
  20.     float tmp = 0.0f;
  21.     int i;
  22.    
  23.     for(i=0; str[i] != '\0'; i++){
  24.         switch(str[i]){
  25.             case '1':
  26.                 if(tmpCount == 0){
  27.                     tmpInt = tmpInt << 1;
  28.                     tmpInt += 1;
  29.                 } else {
  30.                     tmpCount = tmpCount << 1;
  31.                     tmp += 1./(float)tmpCount;
  32.                 }
  33.                 break;
  34.             case '0':
  35.                 if(tmpCount == 0){
  36.                     tmpInt = tmpInt << 1;
  37.                 } else {
  38.                     tmpCount = tmpCount << 1;
  39.                 }
  40.                 break;
  41.             case '.':
  42.                 tmpCount = 1;
  43.                 break;
  44.             default:
  45.                 if(tratarRuido){
  46.                     return -1.0f;
  47.                 }
  48.         }
  49.     }
  50.  
  51.     tmp = tmp + (float)tmpInt;
  52.  
  53.     return tmp;
  54. }
  55.  
  56. float binToFloat(const char* str){
  57.     return binToFloat(str, 0);
  58. }
Advertisement
Add Comment
Please, Sign In to add comment