ASCII to Hex Encoding
Site Map Feedback
Up ASCIIHex Base32 Base64 MIME QuotedPrintable URL UU
Here are a couple of helper functions that will convert a CString of binary data to Hex and back.
CStrings hold the length of the string, so the string can hold zero Bytes without being truncated.
The Hex string will be twice as long as the original data.
CString ASCIIhex2Data(const CString& S) { // A helper function for ASCII Hex to Data
  CString Data;
  int Len=S.GetLength()/2;
  const char* src=S;
  char* dst=Data.GetBufferSetLength(Len);
  for(int i=0; i<Len; ++i) {
    BYTE hi=*src++;
    hi-=(hi<'A' ? '0' : 'A'-10);
    BYTE lo=*src++;
    lo-=(lo<'A' ? '0' : 'A'-10);
    *dst++=(hi<<4) | (lo & 0x0F); // " & 0x0F" deals with lower-case characters
  }
  Data.ReleaseBuffer(Len);
  return Data;
}
CString Data2ASCIIhex(const CString& S) { // A helper function for Data to ASCII Hex
  if(S.IsEmpty()) return "";
  CString Text;
  int Len=S.GetLength()*2;
  const char* src=S;
  char* dst=Text.GetBufferSetLength(Len);
  for(int i=S.GetLength(); i--;) {
    BYTE lo=*src++;
    BYTE hi=lo>>4;
    lo&=0x0F;
    *dst++=hi+(hi>9 ? 'A'-10 : '0');
    *dst++=lo+(lo>9 ? 'A'-10 : '0');
  }
  Text.ReleaseBuffer(Len);
  return Text;
}

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


 (2346) Last modified: Tue, 03 Feb 2009 18:26:07 +0000