Embedded System Design 2 - Project
util_string.c
Go to the documentation of this file.
1 /* ____ ____ _ __ __ ____ ___
2  * | _ \| _ \ / \ | \/ |/ ___/ _ \
3  * | | | | |_) | / _ \ | |\/| | | | | | |
4  * | |_| | _ < / ___ \| | | | |__| |_| |
5  * |____/|_| \_\/_/ \_\_| |_|\____\___/
6  * research group
7  * dramco.be/
8  *
9  * KU Leuven - Technology Campus Gent,
10  * Gebroeders De Smetstraat 1,
11  * B-9000 Gent, Belgium
12  *
13  * File: util.c
14  * Created: 2018-01-19
15  * Author: Guus Leenders - Modified by Brecht Van Eeckhoudt
16  * Version: 1.1 (1.0 -> 1.1: Added comment about malloc)
17  *
18  * Description: TODO
19  */
20 
21 #include <stdint.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <stdbool.h>
25 #include <string.h>
26 
27 bool StringStartsWith(char * str, char * seq){
28  uint8_t i;
29  for(i=0; i<strlen(seq); i++){
30  if(*(str+i) != *(seq+i)){
31  return (false);
32  }
33  }
34  return (true);
35 }
36 
37 bool HexToString(uint8_t * bin, uint8_t binsz, char **result ){
38  char hex_str[] = "0123456789abcdef";
39  uint8_t i;
40 
41  // ALLOCATE MEMORY
42  // Hex to string/char array: one value becomes two chars (*2)
43  // +1 because of NULL termination
44  // "*result =" ~ Value at memory location gets changed
45  if (!(*result = (char *)malloc(binsz * 2 + 1))){
46  return (false); // Returned when NULL
47  }
48 
49  // Add NULL termination
50  (*result)[binsz * 2] = 0; // Last memory location, "0" ~ '\0'
51 
52  // CHECK MEMORY
53  if (!binsz){
54  return (false); // Returned when NULL
55  }
56 
57  // FILL WITH DATA
58  for (i = 0; i < binsz; i++){
59  (*result)[i * 2 + 0] = hex_str[(bin[i] >> 4) & 0x0F];
60  (*result)[i * 2 + 1] = hex_str[(bin[i] ) & 0x0F];
61  }
62 
63  return (true);
64 }
65 
66 char * StringToHexString(char * bin, unsigned int binsz, char **result ){
67  char hex_str[] = "0123456789abcdef";
68  unsigned int i;
69 
70  if (!(*result = (char *)malloc(binsz * 2 + 1))){
71  return (NULL);
72  }
73 
74  (*result)[binsz * 2] = 0;
75 
76  if (!binsz){
77  return (NULL);
78  }
79 
80  for (i = 0; i < binsz; i++){
81  (*result)[i * 2 + 0] = hex_str[(bin[i] >> 4) & 0x0F];
82  (*result)[i * 2 + 1] = hex_str[(bin[i] ) & 0x0F];
83  }
84 
85  return (*result);
86 }
bool HexToString(uint8_t *bin, uint8_t binsz, char **result)
Definition: util_string.c:37
char * StringToHexString(char *bin, unsigned int binsz, char **result)
Definition: util_string.c:66
bool StringStartsWith(char *str, char *seq)
Definition: util_string.c:27