Sam Grove / atoh

Dependents:   Nucleo_read_hyperterminale

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers atoh.cpp Source File

atoh.cpp

Go to the documentation of this file.
00001 /**
00002  * @file   atoh.cpp
00003  * @brief  Convert an ASCII hex string to hexadecimal - seems like the 
00004  *  std library should include this... maybe it does. Just couldn't find it
00005  * @author  sam grove
00006  * @version 1.0
00007  *
00008  * Copyright (c) 2013
00009  *
00010  * Licensed under the Apache License, Version 2.0 (the "License");
00011  * you may not use this file except in compliance with the License.
00012  * You may obtain a copy of the License at
00013  *
00014  *     http://www.apache.org/licenses/LICENSE-2.0
00015  *
00016  * Unless required by applicable law or agreed to in writing, software
00017  * distributed under the License is distributed on an "AS IS" BASIS,
00018  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00019  * See the License for the specific language governing permissions and
00020  * limitations under the License.
00021  */
00022  
00023 #include "atoh.h"
00024 
00025 template<typename T>
00026 T atoh( char const *string )
00027 {
00028     T value = 0;
00029     char ch = 0;
00030     uint8_t digit = 0, bail = sizeof(T) << 1;
00031     
00032     // loop until the string has ended
00033     while ( ( ch = *(string++) ) != 0 ) 
00034     {
00035         // service digits 0 - 9
00036         if ( ( ch >= '0' ) && ( ch <= '9' ) ) 
00037         {
00038             digit = ch - '0';
00039         }
00040         // and then lowercase a - f
00041         else if ( ( ch >= 'a' ) && ( ch <= 'f' ) ) 
00042         {
00043             digit = ch - 'a' + 10;
00044         }
00045         // and uppercase A - F
00046         else if ( ( ch >= 'A' ) && ( ch <= 'F' ) ) 
00047         {
00048             digit = ch - 'A' + 10;
00049         }
00050         // stopping where we are if an inapproprate value is found
00051         else 
00052         {
00053             break;
00054         }
00055         // if the return is 8, 16, or 32 bits - only parse that amount
00056         if ( bail-- == 0 )
00057         {
00058             break;
00059         }
00060         // and build the value now, preparing for the next pass
00061         value = (value << 4) + digit;
00062     }
00063 
00064     return value;
00065 }
00066 
00067 template uint8_t  atoh <uint8_t> (const char* string );
00068 template uint16_t atoh <uint16_t>(const char* string );
00069 template uint32_t atoh <uint32_t>(const char* string );
00070 template uint64_t atoh <uint64_t>(const char* string );
00071