convert.c 2.47 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* VideoLAN VLANbridge: Type conversions
 *
 * Benoit Steiner, ECP, <benny@via.ecp.fr>
 *
*/


#include <stdio.h>
#include "debug.h"


/*****************************************************************************/
/* Convert an ascii char into the corresponding hexadecimal integer          */
/* (between 0 and 16)                   		        	     */
/*****************************************************************************/
inline int ascii2hexa (char s)
{
18 19
  /* Do uppercase */
  if (s >= 'a' && s <= 'f')
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    s -= ('a' - 'A');

  return (s > '9')?10 + s - 'A':s - '0';
}


/*****************************************************************************/
/* Convert an hexadecimal integer between 0 and 16 to the corresponding	     */
/* ascii char (in uppercase)						     */
/*****************************************************************************/
inline char hexa2ascii(int i)
{
  return (i > 9)?'A' + (i-10):'0' + i;
}


/*****************************************************************************/
/* Convert MAC address from its ASCII form to binary                         */
/* Beware: binary form is not in network byte order !                        */
/*****************************************************************************/
int mac_atob (char* MAC, unsigned char* mac_addr)
{
  int hex, n;
  int iRc = 0;

  ASSERT(MAC);
  ASSERT(mac_addr);

  if (strlen (MAC) == 17)	/* Good MAC address length */
  {
    for (n = 0; n < 6; n++)
    {
       hex = 16 * ascii2hexa (MAC[3*n]) + ascii2hexa (MAC[3*n+1]);

      if (hex < 0 || hex > 255)
	iRc = 1;		/* Bad MAC address format */
      else
	mac_addr[n] = hex;	/* Good MAC address format */
    }
  }
  else
    iRc = 1; /* Bad MAC address format */

  return iRc;
}


/*****************************************************************************/
/* Convert MAC address previously got from mac_atob from its binary form     */
/* into ASCII                                                                */
/*****************************************************************************/
int mac_btoa (char* MAC, unsigned char* mac_addr)
{
  int n;
  int iRc = 0;

  ASSERT(MAC);
  ASSERT(mac_addr);

  /* Write down separators between octets */
  for (n = 0; n < 5; n++)
    MAC[3*n+2] = ':';

  /* Write the octets in hexadecimal format */
  for (n = 0; n < 6; n++)
  {
    MAC[3*n] = hexa2ascii((mac_addr[n]>>4)&15);	/* mac_addr[n] & 11110000 */
    MAC[3*n+1] = hexa2ascii((mac_addr[n]&15));	/* mac_addr[n] & 00001111 */
  }

  return iRc;
}