Last active
August 29, 2015 14:08
-
-
Save torinkwok/b229ef35ea4a5b8e20e7 to your computer and use it in GitHub Desktop.
Convert Hex To Decimal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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