长整数装化为16进制的字符串
字符串的大小写转换
判定一个字符
#include <iostream>
using namespace std;
static const char hex_chars[] = "0123456789abcdef";
string long_to_hex(unsigned long value)
{
string str_hex;
int shift = 0;
unsigned long copy = value;
while (copy)
{
copy >>= 4;
shift++;
}
if (shift == 0)
shift++;
if (shift & 0x01)
shift++; //保证shift至少为2
shift <<= 2;//shift此时变为二进制的bit位数,四的倍数
while (shift > 0)
{
shift -= 4;//一次循环处理四位
str_hex += hex_chars[(value >> shift) & 0x0F];
}
return str_hex;
}
int main()
{
cout<<long_to_hex(56);
return 0;
}
字符串的大小写转换
#include <stdio.h>
#include <stdlib.h>
int to_upper(char *c)
{
if (!c) return 0;
for ( ; *c; c++)
{
if (*c >= 'a' && *c <= 'z')
{
*c &= ~32;
//A-Z:65-90 a-z:97-122 可见不同在于表示32的那个二进制比特位
//小变大相当于去掉32那个比特位,可通过&(~32)实现
}
}
return 0;
}
int to_lower(char *c)
{
if (!c) return 0;
for ( ; *c; c++)
{
if (*c >= 'A' && *c <= 'Z')
{
*c |= 32;
}
}
//大变小相当于增加32那个比特位,可通过|32实现
return 0;
}
int main()
{
char test[]="hello WORLD!";
//原因:此时"hello world!"被当做非常量字符串,放在了栈上,允许修改
//char* test="hello world!"; 为什么这么写会报错?
//原因:此时"hello world!"被当做常量字符串,放在了静态存储区,不允许修改
to_upper(test);
printf("%s\n",test);
to_lower(test);
printf("%s\n",test);
return 0;
}
判定一个字符
#include <stdio.h>
#include <stdlib.h>
//注:参数是字符的ascii值.
//检测给定字符是否为数字字符
int light_isdigit(int c)
{
return (c >= '0' && c <= '9');
}
//检测给定字符是否为十六进制数字字符
int light_isxdigit(int c)
{
if (light_isdigit(c)) return 1;
c |= 32; //统一转化为小写
return (c >= 'a' && c <= 'f');
}
//检测给定字符是否为字母字符
int light_isalpha(int c)
{
c |= 32;
return (c >= 'a' && c <= 'z');
}
//检测给定字符是否为数字字符或字母字符
int light_isalnum(int c)
{
return light_isdigit(c) || light_isalpha(c);
}
int main()
{
printf("%d\n",light_isdigit('8'));
printf("%d\n",light_isdigit(8));
printf("%d\n",light_isalpha('a'));
printf("%d\n",light_isalpha(97));
return 0;
}