字符串转换成二进制(限定只转换大小写字母)

版权声明:本文为博主原创文章,欢迎转载,但请标出本文的出处,谢谢!欢迎访问本人的github主页【https://github.com/abodu/omb】 https://blog.csdn.net/liudglink/article/details/83001713
//=================================================================
// CPSTR: Copyright (c) 2018 By Abodu, All Rights Reserved.
// FNAME: main.c
// AUTHR: abodu,[email protected]
// CREAT: 2018-10-11 17:42:19
// ENCOD: UTF-8 Without BOM
// VERNO: 0.0.6
// LUPTS: 2018-10-11 17:42:45
//=================================================================

#include <stdio.h>

void dectobin(int n)
{
  int k = 1;
  long result = 0;

  while (n)
  {
    result += k * (n % 2);
    k *= 10;
    n /= 2;
  }

  printf("%08d ", result);

}

void str_to_binary(char* src)
{
  if (!src || !src[0] ) //if (NULL == src || 0 == src[0] )
  {
    printf("parameter [src] must not an empty string\n");
    return;
  }

  char* p = src;
  while ( *p ) //( 0 != p[0] )
  {
    if ('a' <= *p  && *p <= 'z')
    {
      dectobin(*p - 'a' + 97);
    }
    else if ('A' <= *p  && *p <= 'Z')
    {
      dectobin(*p - 'a' + 65);
    }
    else
    {
      printf("%c ", *p);
    }

    p++;
  }

  printf("\n");
}

int main(int argc, char* argv[])
{
  if(1 == argc)
  {
    str_to_binary("xiexiaohui");
  }
  else
  {
    str_to_binary(argv[1]);
  }
  
  return 0;
}

猜你喜欢

转载自blog.csdn.net/liudglink/article/details/83001713