Advertisement
ccmny

uint2hex

Apr 14th, 2011
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.27 KB | None | 0 0
  1. void UIntToHexStr(unsigned int uiValue, char cStr[]){
  2.  
  3.     unsigned int uiNibble;
  4.     unsigned char ucNibbleCounter;
  5.  
  6.     cStr[0] = '0';
  7.     cStr[1] = 'x';
  8.     for(ucNibbleCounter = 0; ucNibbleCounter < 4; ucNibbleCounter++){
  9.         uiNibble = ((uiValue >> (4 * ucNibbleCounter)) & 0xF);
  10.         if(uiNibble < 10){
  11.             cStr[5 - ucNibbleCounter] = uiNibble + '0';
  12.         }
  13.         else{
  14.             cStr[5 - ucNibbleCounter] = uiNibble + 'A' - 10;
  15.         }
  16.     }
  17.     cStr[6] = NULL;
  18. }
  19.  
  20. enum Result eHexStringToUInt(char cStr[], unsigned int *puiValue){
  21.  
  22.     unsigned char ucLoopCounter;
  23.     char cStrElement;
  24.  
  25.     *puiValue = 0;
  26.     if((cStr[0] != '0') || (cStr[1] != 'x') || (cStr[2] == NULL)){
  27.         return ERROR;
  28.     }
  29.     for(ucLoopCounter = 2; *(cStr + ucLoopCounter) != NULL; ucLoopCounter++){
  30.         cStrElement = cStr[ucLoopCounter];
  31.         if (ucLoopCounter > 5){
  32.             return ERROR;
  33.         }
  34.         else if(cStrElement >= '0' && cStrElement <= '9'){
  35.             *puiValue = (*puiValue << 4) + cStrElement - 48;
  36.         }
  37.         else if(cStrElement >= 'A' && cStrElement <= 'F'){
  38.             *puiValue = (*puiValue << 4) + cStrElement - 55;
  39.         }
  40.         else{
  41.             return ERROR;
  42.         }
  43.     }
  44.     return OK;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement