/* * Copyright (c) 2001 by Cliff Green. All rights reserved. Individual files * may be covered by other copyrights (as noted in the file itself). * * Redistribution and use in source and binary forms are permitted * provided that this entire copyright notice is duplicated in all such * copies. * * This software is provided "as is" and without any expressed or implied * warranties, including, without limitation, the implied warranties of * merchantibility and fitness for any particular purpose. */ //---------------------------------------------------------------------- // Source file: binarybuf.cpp // Written by: Cliff Green, 2001 // Compiler: Metrowerks CodeWarrior Pro 6 // History: // Modified: 9/09/2001 // By: Cliff Green // Comments: See header file. //---------------------------------------------------------------------- #include "binarybuf.h" #include namespace Util { // Slight bit of non-portability in this function - there's an assumption // of 8-bit characters, which is a fairly safe assumption for modern // platforms. const std::string toHex (const unsigned char* buf, size_t len) { static const char hexChars [] = "0123456789ABCDEF"; std::string hexStr; hexStr.reserve(len*2); for (size_t i (0); i < len; ++i) { hexStr += hexChars [ buf[i] / 16 ]; hexStr += hexChars [ buf[i] % 16 ]; } return hexStr; } // Pre-condition: c is valid hex char, 0-9, A-F unsigned char fromHex (char c) { return static_cast((isdigit(c) ? c - '0' : c - 'A' + 10)); } // Pre-conditions for this function: even number of characters in buf, // valid hex chars in string, 'A' - 'F' are uppercase. const BinBufUnChar fromHex ( const std::string& buf) { BinBufUnChar binBuf; binBuf.reserve(buf.length() / 2); for (std::string::size_type i(0); i < buf.length(); i+=2) { binBuf += static_cast(fromHex(buf[i]) * 16 + fromHex(buf[i+1])); } return binBuf; } } // end namespace