med benzekri
med benzekri

Reputation: 603

rgb to hex return wrong value when giving rgb(1,2,3) in c

i am still a beginner with c and am writing a converter RGB to HEX for "code wars" challenge which would for e.g return 010203 when i give rgb(1,2,3) but it returns 030303 i have checked my converting logic and its correct (i guess)
this is my code:

#include <string.h>
#include <stdio.h>

char* convert(int num){
    int rem;
    char deg[17]="0123456789ABCDEF";
    static char ret[3];
    rem=num%16;
    num=num/16;
    ret[0]=deg[num];
    ret[1]=deg[rem];
    return ret;
}

int rgb(int r, int g, int b, char *output)
{
    snprintf(output,sizeof(output),"%s%s%s",convert(r),convert(g),convert(b));
    return 0; 
}

i have tried also replacing snpritf by strcat but then insted of returning 00FF7D it return 37D when giving rgb(0,255,125)
this is how replaced snpritf by strcat:

  strcat(output,convert(r));
  strcat(output,convert(g));
  strcat(output,convert(b));

i am really confused any help is appreciated.

Upvotes: 1

Views: 99

Answers (2)

prog-fh
prog-fh

Reputation: 16785

Because you return the address of a static array of char, your three calls to convert() all return the same address.

Each call overwrites the array then replaces what was done by the previous calls.

You should create three distinct arrays in rgb() and pass one of each as a parameter to each of the calls to convert().

Another solution is to simplify a bit as below. Because we know that convert() must write two characters, simple pointer arithmetic with step 2 can do the trick. By the way, don't forget the string termination (\0) in convert() (with your static array it was implicit, but now you have to explicitly initialise with 0).

/**
  gcc -std=c99 -o prog_c prog_c.c \
      -pedantic -Wall -Wextra -Wconversion \
      -Wc++-compat -Wwrite-strings -Wold-style-definition -Wvla \
      -g -O0 -UNDEBUG -fsanitize=address,undefined
**/

#include <stdio.h>

void
convert(int num,
        char *result)
{
  const char *deg="0123456789ABCDEF";
  result[0]=deg[num/16];
  result[1]=deg[num%16];
  result[2]='\0';
}

int
rgb(int r, int g, int b,
    char *output, size_t capacity)
{
  if(capacity<7)
  {
    return -1;
  }
  convert(r, output+0);
  convert(g, output+2);
  convert(b, output+4);
  return 0; 
}

int
main(void)
{
  char txt[20];
  rgb(1, 2, 3, txt, sizeof(txt));
  printf("%s\n", txt);
  return 0;
}

Upvotes: 2

Barmar
Barmar

Reputation: 780724

Your second attempt was almost right, but you need to use strcpy() for the first string, unless output is initialized to an empty string.

void rgb(int r, int g, int b, char *output)
{
    strcpy(output,convert(r));
    strcat(output,convert(g));
    strcat(output,convert(b));
    return; 
}

Upvotes: 1

Related Questions