Skip to content

Instantly share code, notes, and snippets.

@torinkwok
Last active August 29, 2015 14:08
Show Gist options
  • Select an option

  • Save torinkwok/b229ef35ea4a5b8e20e7 to your computer and use it in GitHub Desktop.

Select an option

Save torinkwok/b229ef35ea4a5b8e20e7 to your computer and use it in GitHub Desktop.
Convert Hex To Decimal
#define COMPARE_WITH_CASE_INSENSITIVE( _Lhs, _Rhs ) \
( [ _Lhs compare: _Rhs options: NSCaseInsensitiveSearch ] == NSOrderedSame ) \
BOOL isCharInAtoE( NSString* );
NSUInteger mapHexAlphaToDecimalNumeric( NSString* _AlphaInHexNumeric );
NSUInteger OMCOperandConvertHexToDecimal( NSString* _HexNumeric )
{
NSString* prefixForHex = @"0x";
if ( ![ _HexNumeric hasPrefix: prefixForHex ] )
return NAN;
NSString* hexNumericWithoutPrefix = [ _HexNumeric substringFromIndex: prefixForHex.length ];
NSUInteger resultInDecimal = 0U;
double exponent = 0.f;
for ( int index = ( int )hexNumericWithoutPrefix.length - 1; index >= 0; index-- )
{
NSString* stringForCurrentDigit = [ hexNumericWithoutPrefix substringWithRange: NSMakeRange( index, 1 ) ];
NSUInteger valueForCurrentDigit = 0U;
if ( isCharInAtoE( stringForCurrentDigit ) )
valueForCurrentDigit = mapHexAlphaToDecimalNumeric( stringForCurrentDigit );
else
valueForCurrentDigit = ( NSUInteger )[ stringForCurrentDigit integerValue ];
resultInDecimal += valueForCurrentDigit * ( NSUInteger )pow( 16, exponent++ );
}
return resultInDecimal;
}
BOOL isCharInAtoE( NSString* _Char )
{
if ( COMPARE_WITH_CASE_INSENSITIVE( _Char, @"A" )
|| COMPARE_WITH_CASE_INSENSITIVE( _Char, @"B" )
|| COMPARE_WITH_CASE_INSENSITIVE( _Char, @"C" )
|| COMPARE_WITH_CASE_INSENSITIVE( _Char, @"D" )
|| COMPARE_WITH_CASE_INSENSITIVE( _Char, @"E" )
|| COMPARE_WITH_CASE_INSENSITIVE( _Char, @"F" ) )
return YES;
else
return NO;
}
NSUInteger mapHexAlphaToDecimalNumeric( NSString* _AlphaInHexNumeric )
{
if ( COMPARE_WITH_CASE_INSENSITIVE( _AlphaInHexNumeric, @"A" ) )
return 10;
if ( COMPARE_WITH_CASE_INSENSITIVE( _AlphaInHexNumeric, @"B" ) )
return 11U;
if ( COMPARE_WITH_CASE_INSENSITIVE( _AlphaInHexNumeric, @"C" ) )
return 12U;
if ( COMPARE_WITH_CASE_INSENSITIVE( _AlphaInHexNumeric, @"D" ) )
return 13U;
if ( COMPARE_WITH_CASE_INSENSITIVE( _AlphaInHexNumeric, @"E" ) )
return 14U;
if ( COMPARE_WITH_CASE_INSENSITIVE( _AlphaInHexNumeric, @"F" ) )
return 15U;
return NAN;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment