gdbutil.c 2.52 KB
/*---------------------------------------------------------------------*
 *  Copyright (C) 2004 BroadOn Communications Corp.
 *                 
 *  $RCSfile: gdbutil.c,v $
 *  $Revision: 1.1 $
 *  $Date: 2004/02/06 02:12:22 $
 *---------------------------------------------------------------------*/

#include "ultragdb.h"

/**************** GDB Utility Functions **************/
const char hexchars[]="0123456789abcdef";

/* Do we need this?  Do we need our own copy of strlen, strncmp. strcmp? */
char *strcpy (char *s1, const char *s2)
{
    char *dest=s1;
    char c;
    
    do {
        c = *s2++;
        *dest++ = c;
    } while (c != 0);
    
    return s1;
}

/* convert the memory pointed to by mem into hex, placing result in buf */
/* return a pointer to the last char put in buf (null) */
char* mem2hex(char *mem, char *buf, int count)
{
      int i;
      unsigned char ch;
      
      if (mem == NULL) return NULL;
      if (buf == NULL) return NULL;

      for (i=0;i<count;i++) {
          ch = *mem++;
          *buf++ = hexchars[ch >> 4];
          *buf++ = hexchars[ch % 16];
      }
      *buf = 0; 
      return(buf);
}

int hex(char ch)
{
  if ((ch >= 'a') && (ch <= 'f')) return (ch-'a'+10);
  if ((ch >= '0') && (ch <= '9')) return (ch-'0');
  if ((ch >= 'A') && (ch <= 'F')) return (ch-'A'+10);
  return (-1);
}

/**********************************************/
/* WHILE WE FIND NICE HEX CHARS, BUILD AN INT */
/* RETURN NUMBER OF CHARS PROCESSED           */
/**********************************************/
int hexToInt(char **ptr, int *intValue)
{
    int sign = 1;
    int numChars = 0;
    int hexValue;

    if ((ptr == NULL) || (*ptr == NULL)) return 0;
    if (intValue == NULL) return 0;
    
    *intValue = 0;

    if (**ptr == '-')
    {
        (*ptr)++;
        sign = -1;
    }

    while (**ptr)
    {
        hexValue = hex(**ptr);
        if (hexValue >=0)
        {
            *intValue = (*intValue <<4) | hexValue;
            numChars ++;
        }
        else
            break;
        
        (*ptr)++;
    }

    (*intValue) *= sign;

    return (numChars);
}

/* convert the hex array pointed to by buf into binary to be placed in mem */
/* return a pointer to the character AFTER the last byte written */
char* hex2mem(char *buf, char *mem, int count)
{
      int i;
      unsigned char ch;

      if (buf == NULL) return NULL;
      if (mem == NULL) return NULL;

      for (i=0;i<count;i++) {
          ch = hex(*buf++) << 4;
          ch = ch + hex(*buf++);
          *mem++ = ch;
      }
      return(mem);
}