C - Char to hexa [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have str:
char *str = "lala";
Now, I would like convert any chars in str to hexadecimal, example:
str = convert(str);
print str: 0x6C 0x61 0x6C 0x61
^ l ^ a ^ l ^ a
How I can do that ?

char *convert(char const *str) {
int len = strlen(str);
char *retVal = (char *)malloc(5 * len);
char *pos = retVal;
int i;
for(i = 0; i < len; ++i, pos += 5) sprintf(pos, i? " 0x%x" : "0x%x", str[i]);
retVal[5 * len - 1] = '\0';
return retVal;
}
Might have missed something, haven't used C for eight years.

Simply by asking printf to do it :
void convert(char* str, size_t length) {
size_t i;
for(i = 0; i < length; i++)
printf("0x%02x ", str[i]);
}

You can achieve it by using this implementation....
#define MAX 100
char *convert(char *str)
{
char *hexStr = (char *)malloc(strnlen(str, MAX) * 5);
if (hexStr == NULL)
return NULL;
int i,j;
for (i=0, j=0; str[i]; j+=5, i++)
sprintf(hexStr + j, "0x%02x ", str[i]);
hexStr[--j] = '\0';
return hexStr;
}

char* x = str - 1;
while(*++x) printf("%02x ", (int) *x); // Print one character in hex
printf("\n") // Finish with a carriage return

Related

String split in c without changing original [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
we have an school asignment to make a specific function of string split
the header and arguments of function is given cannot change them .
this function should split original by delimiter into array of string that store each part of string delimiter not included and in additon for each delimiter increase size
void stringSplit(const char *original, char result[50][256], int* size, char delim){
size_t begin = 0;
if(!original){
return;
}
for(size_t i=0; i<strlen(original);i++ ){
if (original[i] == delim){
int str_begin = 0;
for( ; begin < i; begin++ ){
result[*size][str_begin] = original[begin];
str_begin++;
}
(*size)++;
begin ++ ;
}
}
}
The idea is OK, but you have a couple of errors:
Your string copies are not '\0'-terminated. Also you are not taking into
account when multiple delimiters follow in a row.
If you are not allowed to use
functions like strchr and strncpy, then you can do this:
size_t str_begin = 0;
*size = 0; // the user may have passed an uninitialized int variable
for(size_t i = 0; original[i] && *size < 50; ++i)
{
if(original[i] == delim)
{
size_t sublen = i - str_begin;
if(sublen == 0)
{
// skip delimiter, last character was also a
// delimiter and/or the first character in
// original is a delimiter
str_begin++;
continue;
// or if you want to have empty words instead of skipping
// results[*size] = 0;
// (*size)++;
}
if(sublen > 256)
sublen = 256;
for(size_t j = 0; j < sublen; ++j)
result[*size][j] = original + str_begin + j;
result[*size][j] = 0; // \0-terminating string
(*size)++;
str_begin = i + 1; // updating str_begin to next char
}
}
The straight forward way of doing so is - as suggested by Barmar - to make a copy of the original string and then work with strtok() and strcpy.
Alternatively, you could use strchr in a loop to find the delimiters and memcpy to copy the memory between the previous delimiter and the next one. See the following code, which also takes the boundaries of the result array into account:
void stringSplit(const char *original, char result[50][256], int *size, char
delim)
{
if(!original){
return ;
}
*size = 0;
const char* nextDelim;
const char* prevDelim = original;
do {
nextDelim = strchr(prevDelim,delim);
size_t len = nextDelim ? (nextDelim - prevDelim) : strlen(prevDelim);
if (len >= 256) {
len = 256-1;
}
memcpy(result[*size],prevDelim,len);
result[*size][len] = '\0';
(*size)++;
prevDelim = nextDelim ? nextDelim+1 : NULL;
}
while(nextDelim && *size < 50);
}
int main() {
char result[50][256];
int size;
stringSplit("Hello, this, is", result, &size, ',');
return 0;
}
Hope it helps.

Compare 2 strings in C and print equal part [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How can I compare 2 strings with maximum length 100 and print the equal part of them, like:
STRING 1 : ABCDEFGHIJKLMNOP
STRING 2 : QWERABCDZXVBERTY
The equal parts of these strings are : ABCD
Please look if this program can help you. It takes the two strings as arguments from the command line.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *substring(char *s, char *t) {
int strlen1 = strlen(s);
int strlen2 = strlen(t);
int len = strlen1 < strlen2 ? strlen1 : strlen2;
int i, j, k;
int longest = 0;
int **ptr = (int **) malloc(2 * sizeof(int *));
static int *ret;
ret = (int *) calloc(strlen1 + 1, sizeof(int));
for (i = 0; i < 2; i++)
ptr[i] = (int *) calloc(strlen2, sizeof(int));
k = 0;
for (i = 0; i < strlen1; i++) {
memcpy(ptr[0], ptr[1], strlen2 * sizeof(int));
for (j = 0; j < strlen2; j++) {
if (s[i] == t[j]) {
if (i == 0 || j == 0) {
ptr[1][j] = 1;
} else {
ptr[1][j] = ptr[0][j - 1] + 1;
}
if (ptr[1][j] > longest) {
longest = ptr[1][j];
k = 0;
ret[k++] = longest;
}
if (ptr[1][j] == longest) {
ret[k++] = i;
ret[k] = -1;
}
} else {
ptr[1][j] = 0;
}
}
}
for (i = 0; i < 2; i++)
free(ptr[i]);
free(ptr);
ret[0] = longest;
return ret;
}
int main(int argc, char *argv[]) {
int i, longest, *ret;
if (argc != 3) {
printf("usage: longest-common-substring string1 string2\n");
exit(1);
}
ret = substring(argv[1], argv[2]);
if ((longest = ret[0]) == 0) {
printf("There is no common substring\n");
exit(2);
}
i = 0;
while (ret[++i] != -1) {
printf("%.*s\n", longest, &argv[1][ret[i] - longest + 1]);
}
exit(0);
}
Test
./a.out ABCDEFGHIJKLMNOP QWERABCDZXVBERTY
ABCD
Compare two strings is a common skill which is very easy to find information. First you should read string.h library where you can find a lot of useful function in order to work with strings.
Then the first stupid algorithm is to compare each char of first string with the second and if it matches you add that char to the result.
But it would be smarter to order the two strings and then compare them, saving many comparisons.

Storing value of unsigned int variable in char array in C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have 4 variables
unsigned r1 = 255, r2 = 204, r3 = 0, r4 = 255;
i need to return them as a string "(255, 204, 0, 255)"
I don't know how to add the integer values to a char *
You can use sprintf for this:
char str[50];
sprintf(str, "(%d, %d, %d, %d)", r1, r2, r3, r4);
Now the string str contains the string (255, 204, 0, 255).
You should mention in your question that you can not use sprintf. If you forget while creating the question, you should mention it later. I suggest you to update your question. However here is an alternative solution without sprintf
#include <stdio.h>
#include <stdlib.h>
int convert(unsigned char number, char* str){
static int k = 1; // static int is important
int i = k, j;
char temp;
if (number == 0){ // handling of 0
str[k++] = '0';
str[k++] = ',';
return k - 1;
}
while(number){
str[k++] = "0123456789ABCDEF"[number % 10]; // get reversed output
number = number / 10;
}
for (j = k - 1; i < j; i++, j--){ // reversing back the string
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
str[k++] = ',';
return k - 1;
}
int main(){
unsigned char r = 255;
unsigned char g = 221;
unsigned char b = 0;
unsigned char a = 245;
char color[20] = {0}; // always initialize all with 0
int last;
color[0] = '(';
convert(r, color);
convert(g, color);
convert(b, color);
last = convert(a, color);
color[last] = ')';
printf("%s\n", color);
return 0;
}
The above answer can be improved a lot if you do it in C++

Alphanumeric String Generation in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Can anyone give me a complete example of how to generate an Alphanumeric String randomly
like (ARG534UJ6) using C ? I'm completely new to C.
void gen_random(char *s, const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
This is not working.
As pointed out by #IngoLeonhardt, use % (sizeof(alphanum) - 1) instead of % sizeof(alphanum)
My guess is that you don't have room for your string, try:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void gen_random(char *s, const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
int main(void)
{
char *str = malloc(8 + 1);
/* initialize random seed: */
srand(time(NULL));
gen_random(str, 8);
printf("%s\n", str);
free(str);
return 0;
}

Why there is an error? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I wrote the following code block I have all the time error in the function find_brackets and calculation. can someone explain to me how to fix it. And the two functions will function together
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void find_brackets(char str[], int len);
void calculation(char str1);
int main(void) {
int len;
char str1[99];
char str[99]; // (4/2)
printf("Enter a math exercises: \n");
gets(str);
len = strlen(str);
find_brackets(str);
calculation(str1);
}
void find_brackets(str[], len) {
char str1[len];
int i, j;
for(i = 0; i < len; i++) {
if(str[i] == '(') {
i++;
while(str[i] != ')') {
str1[j] = str[i];
i++;
j++;
}
}
}
}
void calculation(str1[], len) {
char str[len];
char strp[len];
char str2[len];
char str3[len];
char *rev;
int i, k, j = 0, aPos, zPos;
int sum1, sum2;
float sum;
strcpy (str, str1);
strcpy (strp, str1);
aPos = zPos = -1;
for(i = 0; i < len; i++) {
if(str[i] == '+') {
aPos = i;
}
else if(str[i] == '/') {
zPos = i;
break;
}
}
if(aPos != -1 && zPos != -1) {
for(k = 0, i = zPos-1; i > aPos; --i, ++k) {
str2[k] = str[i];
}
}
rev = strrev(str2);
printf("%s\n", rev);
for(i = 0; i < len; i++) {
if(strp[i] == '/') {
while(strp[i+1] != '+') {
str3[j++] = strp[++i];
}
}
}
printf("%s\n", str2);
sum1 = atoi(str2);
sum2 = atoi(str3);
sum = sum1 / sum2;
printf("%.0f\n", sum);
}
Thanks for the help I appreciate it
Function declaration is void find_brackets(char str[], int len); and the caller from main() is find_brackets(str); which is wrong. Where is the 2nd arg.
Also function calculation() has differnce in declaration and how it is invoked. Maintain a match in function formal arguments followed by callee actual arguments passed.
void find_brackets(str[],len)
void calculation(str1[],len)
please specify data type of len and str[] at function definations.
Also
find_brackets(str);
calculation(str1);
which pass one argument but you declared that with two which is also wrong.

Resources