string2val.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*******************************************************************************
  2. Copyright 2017 Yepkit Lda (www.yepkit.com)
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. *******************************************************************************/
  13. #include "string2val.h"
  14. #include <stdlib.h>
  15. #include <stdio.h>
  16. /*****************************************************************
  17. * Function:
  18. *
  19. * Description:
  20. *
  21. * Inputs:
  22. *
  23. * Outputs:
  24. *
  25. * Precedences:
  26. *
  27. *****************************************************************/
  28. int char2int(char input)
  29. {
  30. if(input >= '0' && input <= '9')
  31. return input - '0';
  32. if(input >= 'A' && input <= 'F')
  33. return input - 'A' + 10;
  34. if(input >= 'a' && input <= 'f')
  35. return input - 'a' + 10;
  36. //throw std::invalid_argument("Invalid input string");
  37. return 0;
  38. }
  39. /*****************************************************************
  40. * Function:
  41. *
  42. * Description:
  43. *
  44. * Inputs:
  45. *
  46. * Outputs:
  47. *
  48. * Precedences:
  49. *
  50. *****************************************************************/
  51. // This function assumes src to be a zero terminated sanitized string with
  52. // an even number of [0-9a-f] characters, and target to be sufficiently large
  53. int hex2bin(char* src, unsigned char* output, int size)
  54. {
  55. //unsigned char *out = (unsigned char*)malloc(size/2);
  56. unsigned char out;
  57. int i;
  58. for(i=0; i<size; i=i+2) {
  59. *(output++) = char2int(src[0])*16 + char2int(src[1]);
  60. src += 2;
  61. }
  62. //printf("\nout = 0x%x\n", *out);
  63. return 0;
  64. }
  65. int dec2bin(char* src, unsigned char* output, int size)
  66. {
  67. //unsigned char *out = (unsigned char*)malloc(size/2);
  68. unsigned char out;
  69. int base;
  70. for(int i = 0; i < size; i++) {
  71. base = 1;
  72. for (int j = 1; j < (size - i); j++) {
  73. base = base * 10;
  74. }
  75. *(output++) = char2int(src[0]) * base;
  76. src++;
  77. }
  78. //printf("\nout = 0x%x\n", *out);
  79. return 0;
  80. }