Saphe Implementation - hexlify.cpp
/**
 * 
 * Written by Uri Sternfeld
 * Last modified: 30/12/2007
 *
 * Copyright (C) 2007-2008
 * Uri Sternfeld (saphesolution@yahoo.com)
 * All Rights Reserved
 * 
 **/
 
#include "hexlify.h"
 
// Convert to upper-case hex string
void Hexlify(const byte* in, unsigned int size, char* out)
{
    for (unsigned int i = 0 ; i < size ; ++i) {
        for (int j = 0 ; j < 2 ; ++j) {
            char nib = (char)((in[i]>>(4-(4*j)))&0xF);
            if (nib < 10) {
                out[(i*2)+j] = nib + '0';
            }
            else {
                out[(i*2)+j] = nib - 10 + 'A';
            }
        }        
    }
    out[size*2] = 0;
}
 
bool Unhexlify(const char* in, unsigned int size, byte* out)
{
    // The size should be even...
    if (size & 1) {
        return false;
    }
 
    for (unsigned int i = 0 ; i < size ; i+=2) {
        unsigned char current = 0;
        for (int j = 0 ; j < 2 ; ++j) {            
            unsigned char nib = 0;            
            if ((in[i+j] >= '0') && (in[i+j] <= '9')) {
                nib = (byte)((in[i+j] - '0')&0xF);
            }
            else if ((in[i+j] >= 'A') && (in[i+j] <= 'F')) {                     
                nib = (byte)((in[i+j] + 10 - 'A')&0xF);
            }
            else if ((in[i+j] >= 'a') && (in[i+j] <= 'f')) {
                nib = (byte)((in[i+j] + 10 - 'a')&0xF);
            }
            else {
                // Illegal hex character                
                return false;
            }
            current |= nib << (4-(j*4));
        }
        out[i/2] = current;
    }
 
    return true;
}

Back to Saphe implementation page

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License