Chinaunix首页 | 论坛 | 博客
  • 博客访问: 260726
  • 博文数量: 84
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 927
  • 用 户 组: 普通用户
  • 注册时间: 2015-03-06 23:00
个人简介

growing

文章分类

全部博文(84)

文章存档

2017年(6)

2016年(61)

2015年(17)

我的朋友

分类: C/C++

2015-11-11 20:01:37

1.把一个字符串转化为整数:比如“12345”->12345

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <windows.h>
  3. #define MAX_INT 0x7FFFFFFF
  4. #define MIN_INT 0x80000000

  5. typedef enum status{
  6. VALID=0,//合法
  7. INVALID,//非法
  8. }status_t;

  9. int str_to_int_core(char *int_str, status_t *s, int symbol)//判断输入的字符是否合法,是则转
  10. {
  11. long long num = 0;
  12. while (*int_str != '\0'){
  13. if (*int_str >= '0' && *int_str <= '9'){
  14. num = num * 10 + symbol*(*int_str - '0');
  15. }
  16. else{
  17. *s = INVALID;
  18. return 2;
  19. }
  20. int_str++;
  21. }
  22. if ( (symbol == 1 && num > MAX_INT) || \
  23. (symbol == -1 && num < (signed int)MIN_INT))//输入的字符虽然合法,但要判断int能否装下
  24. {
  25. printf("num is overflow!\n");
  26. *s = INVALID;
  27. return 3;
  28. }
  29. return (int)num;
  30. }
  31. int str_to_int(char *int_str, status_t *s)
  32. {
  33. *s = VALID;
  34. if (NULL == int_str || *int_str == '\0' || NULL == s){
  35. *s = INVALID;
  36. return 1;
  37. }
  38. int symbol = 1;
  39. if (*int_str == '+'){
  40. int_str++;
  41. }
  42. else if (*int_str == '-'){
  43. symbol = -1;
  44. int_str++;
  45. }
  46. else{
  47. //DO NOTHING
  48. }
  49. return str_to_int_core(int_str, s, symbol);

  50. }

  51. int main()
  52. {
  53. char int_str[] = "-123456";
  54. status_t s;
  55. int ret_int = str_to_int(int_str, &s);
  56. if (s == VALID){
  57. printf("result int : %d\n", ret_int);
  58. }
  59. else{
  60. printf("errno code : %d\n", ret_int);
  61. }
  62. system("pause");
  63. return 0;
  64. }
2.把一个二进制数的一位置1或置0,其它为保持不变


点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <windows.h>
  3. void show_bit(unsigned char bit_8)
  4. {
  5. int i = 0;
  6. unsigned char flag = 0x80; //1000 0000
  7. for (; i < sizeof(unsigned char)* 8; i++){
  8. if (flag & bit_8){
  9. printf("1");
  10. }
  11. else{
  12. printf("0");
  13. }
  14. flag >>= 1;
  15. }
  16. printf("\n");
  17. }

  18. #define _ZERO_ 0//for flag
  19. #define _ONE_ 1
  20. void bit_set(unsigned char *p_data, unsigned char pos, int flag)
  21. {
  22. if (flag == _ZERO_)
  23. {
  24. *p_data &= ~(0x1 << pos);
  25. }
  26. else if (flag == _ONE_)
  27. {
  28. *p_data |= (0x1 << pos);
  29. }
  30. else
  31. {
  32. return;
  33. }
  34. }

  35. int main()
  36. {
  37. unsigned char tmp = 0x0f;
  38. show_bit(tmp);
  39. bit_set(&tmp, 7, _ONE_);
  40. show_bit(tmp);
  41. bit_set(&tmp, 0, _ZERO_);
  42. show_bit(tmp);
  43. system("pause");
  44. return 0;
  45. }

阅读(1155) | 评论(0) | 转发(0) |
0

上一篇:yum一些常用指令

下一篇:常用指令

给主人留下些什么吧!~~