xref: /netbsd-src/external/bsd/elftosb/dist/common/HexValues.cpp (revision 993229b6fea628ff8b1fa09146c80b0cfb2768eb)
1*993229b6Sjkunz /*
2*993229b6Sjkunz  * File:	HexValues.cpp
3*993229b6Sjkunz  *
4*993229b6Sjkunz  * Copyright (c) Freescale Semiconductor, Inc. All rights reserved.
5*993229b6Sjkunz  * See included license file for license details.
6*993229b6Sjkunz  */
7*993229b6Sjkunz 
8*993229b6Sjkunz #include "HexValues.h"
9*993229b6Sjkunz 
isHexDigit(char c)10*993229b6Sjkunz bool isHexDigit(char c)
11*993229b6Sjkunz {
12*993229b6Sjkunz 	return isdigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
13*993229b6Sjkunz }
14*993229b6Sjkunz 
15*993229b6Sjkunz //! \return The integer equivalent to \a c.
16*993229b6Sjkunz //! \retval -1 The character \a c is not a hex character.
hexCharToInt(char c)17*993229b6Sjkunz uint8_t hexCharToInt(char c)
18*993229b6Sjkunz {
19*993229b6Sjkunz 	if (c >= '0' && c <= '9')
20*993229b6Sjkunz 		return c - '0';
21*993229b6Sjkunz 	else if (c >= 'a' && c <= 'f')
22*993229b6Sjkunz 		return c - 'a' + 10;
23*993229b6Sjkunz 	else if (c >= 'A' && c <= 'F')
24*993229b6Sjkunz 		return c - 'A' + 10;
25*993229b6Sjkunz 	else
26*993229b6Sjkunz 		return static_cast<uint8_t>(-1);
27*993229b6Sjkunz }
28*993229b6Sjkunz 
29*993229b6Sjkunz //! \param encodedByte Must point to at least two ASCII hex characters.
30*993229b6Sjkunz //!
hexByteToInt(const char * encodedByte)31*993229b6Sjkunz uint8_t hexByteToInt(const char * encodedByte)
32*993229b6Sjkunz {
33*993229b6Sjkunz 	return (hexCharToInt(encodedByte[0]) << 4) | hexCharToInt(encodedByte[1]);
34*993229b6Sjkunz }
35