2013-02-03 21 views
0

我需要使用GNU C printf函數來發送浮點數到半主機控制檯。 當前實現的printf(vsnprintf)是實現printf進行漂浮在GNU C中,半主機

signed int vsnprintf(char *pStr, size_t length, const char *pFormat, va_list ap) 
{ 
    char   fill; 
    unsigned char width; 
    signed int num = 0; 
    signed int size = 0; 

    /* Clear the string */ 
    if (pStr) { 

     *pStr = 0; 
    } 

    /* Phase string */ 
    while (*pFormat != 0 && size < length) { 

     /* Normal character */ 
     if (*pFormat != '%') { 

      *pStr++ = *pFormat++; 
      size++; 
     } 
     /* Escaped '%' */ 
     else if (*(pFormat+1) == '%') { 

      *pStr++ = '%'; 
      pFormat += 2; 
      size++; 
     } 
     /* Token delimiter */ 
     else { 

      fill = ' '; 
      width = 0; 
      pFormat++; 

      /* Parse filler */ 
      if (*pFormat == '0') { 

       fill = '0'; 
       pFormat++; 
      } 

      /* Parse width */ 
      while ((*pFormat >= '0') && (*pFormat <= '9')) { 

       width = (width*10) + *pFormat-'0'; 
       pFormat++; 
      } 

      /* Check if there is enough space */ 
      if (size + width > length) { 

       width = length - size; 
      } 

      /* Parse type */ 
      switch (*pFormat) { 
      case 'd': 
      case 'i': num = PutSignedInt(pStr, fill, width, va_arg(ap, signed int)); break; 
      case 'u': num = PutUnsignedInt(pStr, fill, width, va_arg(ap, unsigned int)); break; 
      case 'x': num = PutHexa(pStr, fill, width, 0, va_arg(ap, unsigned int)); break; 
      case 'X': num = PutHexa(pStr, fill, width, 1, va_arg(ap, unsigned int)); break; 
      case 's': num = PutString(pStr, va_arg(ap, char *)); break; 
      case 'c': num = PutChar(pStr, va_arg(ap, unsigned int)); break; 
      default: 
       return EOF; 
      } 

      pFormat++; 
      pStr += num; 
      size += num; 
     } 
    } 

    /* NULL-terminated (final \0 is not counted) */ 
    if (size < length) { 

     *pStr = 0; 
    } 
    else { 

     *(--pStr) = 0; 
     size--; 
    } 

    return size; 
} 

任何有助於實現「F」格式說明是極大的讚賞

+0

這是不完全清楚。如果你「需要使用GNU C printf」,你爲什麼不使用它? –

+0

你可以在代碼中看到vsprintf的實現不支持'f'格式說明符。這就是爲什麼它不能按原樣使用! – TonyP

+0

起初我會哭泣犯規,因爲他們沒辦法忽略它,但後來我看了看標籤。你在一個手臂系統。沒有浮點。只要看看x86或類似的實現。 –

回答

0

看來你使用自定義printf的實現,而不是使用一個從libc的工具鏈。只要你已經實現了syscalls,你應該能夠僅僅通過簡單地在你的stdio的實現不能編譯切換到標準printf執行的工具鏈。

的另一種方式可以是,使一個PutFloat函數簡單地通過10的冪相乘的輸入,然後分別打印使用現有的整數打印數的上方和下方小數部分。例如:

x = (signed int)floatIn*10000; 
PutSignedInt(x/10000); 
PutChar('.'); 
ax = abs(x); 
ay = abs(y); 
ax = ax - ay*10000; 
PutSignedInt(ax); 

如果你的想法,你應該能夠填補細節自己。