c# 字符与16进制互转

来源:互联网 发布:qq for mac 编辑:程序博客网 时间:2024/06/08 18:54

转载连接: http://blog.csdn.net/ooyyee/article/details/54692953?locationNum=9&fps=1


  1. #include <stdio.h>
  2. #include <string.h>

  3. int strToHex(char *ch, char *hex);
  4. int hexToStr(char *hex, char *ch);
  5. int hexCharToValue(const char ch);
  6. char valueToHexCh(const int value);
  7. int main(int argc, char *argv[])
  8. {
  9.     char ch[1024];
  10.     char hex[1024];
  11.     char result[1024];
  12.     char *p_ch = ch;
  13.     char *p_hex = hex;
  14.     char *p_result = result;
  15.     printf("please input the string:");
  16.     scanf("%s",p_ch);

  17.     strToHex(p_ch,p_hex);
  18.     printf("the hex is:%s\n",p_hex);
  19.     hexToStr(p_hex, p_result);
  20.     printf("the string is:%s\n", p_result);
  21.     return 0;
  22. }

  23. int strToHex(char *ch, char *hex)
  24. {
  25.   int high,low;
  26.   int tmp = 0;
  27.   if(ch == NULL || hex == NULL){
  28.     return -1;
  29.   }

  30.   if(strlen(ch) == 0){
  31.     return -2;
  32.   }

  33.   while(*ch){
  34.     tmp = (int)*ch;
  35.     high = tmp >> 4;
  36.     low = tmp & 15;
  37.     *hex++ = valueToHexCh(high); //先写高字节
  38.     *hex++ = valueToHexCh(low); //其次写低字节
  39.     ch++;
  40.   }
  41.   *hex = '\0';
  42.   return 0;
  43. }

  44. int hexToStr(char *hex, char *ch)
  45. {
  46.   int high,low;
  47.   int tmp = 0;
  48.   if(hex == NULL || ch == NULL){
  49.     return -1;
  50.   }

  51.   if(strlen(hex) %== 1){
  52.     return -2;
  53.   }

  54.   while(*hex){
  55.     high = hexCharToValue(*hex);
  56.     if(high < 0){
  57.       *ch = '\0';
  58.       return -3;
  59.     }
  60.     hex++; //指针移动到下一个字符上
  61.     low = hexCharToValue(*hex);
  62.     if(low < 0){
  63.       *ch = '\0';
  64.       return -3;
  65.     }
  66.     tmp = (high << 4) + low;
  67.     *ch++ = (char)tmp;
  68.     hex++;
  69.   }
  70.   *ch = '\0';
  71.   return 0;
  72. }

  73. int hexCharToValue(const char ch){
  74.   int result = 0;
  75.   //获取16进制的高字节位数据
  76.   if(ch >= '0' && ch <= '9'){
  77.     result = (int)(ch - '0');
  78.   }
  79.   else if(ch >= 'a' && ch <= 'z'){
  80.     result = (int)(ch - 'a') + 10;
  81.   }
  82.   else if(ch >= 'A' && ch <= 'Z'){
  83.     result = (int)(ch - 'A') + 10;
  84.   }
  85.   else{
  86.     result = -1;
  87.   }
  88.   return result;
  89. }

  90. char valueToHexCh(const int value)
  91. {
  92.   char result = '\0';
  93.   if(value >= 0 && value <= 9){
  94.     result = (char)(value + 48); //48为ascii编码的‘0’字符编码值
  95.   }
  96.   else if(value >= 10 && value <= 15){
  97.     result = (char)(value - 10 + 65); //减去10则找出其在16进制的偏移量,65为ascii的'A'的字符编码值
  98.   }
  99.   else{
  100.     ;
  101.   }

  102.   return result;
  103. }

原创粉丝点击