-1

Basically, I have this function here that spits out a hexadecimal value when a decimal value is entered. This code works perfectly fine but when I insert it verbatim into a larger set of code I am working on, the hexadecimal number spit out has 8 extra unnecessary characters followed by the correct hexadecimal value. Any thoughts on how to fix it? I was told to terminate the string hexadecimal but where do I do that exactly and how?

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

int main(void){

 int decimalnum, quotient, remainder;
 int k, l = 0;
 char hexadecimalnum[100];
 char str[50];
 int m;
 char temp;
 int j;

 printf("enter decimal number: ");
 scanf("%d", &decimalnum);

 quotient = decimalnum;

 while (quotient != 0) {
    remainder = quotient % 16;
    if(remainder < 10) {
       hexadecimalnum[l++] = 48 + remainder;
    }
    else {
       hexadecimalnum[l++] = 55 + remainder;

    }
    quotient = quotient / 16;
 }

 // Display integer to character.
 for(k = l; k >= 0; k--) {
    str[k] = hexadecimalnum[k];
 }

 m = 0;
 j = l-1;
 // Flip the string because it is written backwards.
 while(m <j) {
    temp = str[m];
    str[m] = str[j];
    str[j] = temp;
    m++;
    j--;
 }
 printf("\n%s\n", str);

 return 0;
  • 1
    Where are you terminating the string? You got add `\0` at the end of the string. – kiran Biradar Oct 09 '18 at 10:36
  • 3
    You forget that `char` strings are really called ***null-terminated** byte strings*. That *null-terminated* bit is important. – Some programmer dude Oct 09 '18 at 10:36
  • 1
    Possible duplicate of [string array with garbage character at end](https://stackoverflow.com/questions/270708/string-array-with-garbage-character-at-end) – kiran Biradar Oct 09 '18 at 10:38
  • On another note, please don't use [*magic numbers*](https://en.wikipedia.org/wiki/Magic_number_(programming)). If by e.g. `55` you mean the ASCII character `'7'` then *say* so. Also note that your conversion into letters isn't guaranteed to work on anything but ASCII, which is not mandated by the C specification. – Some programmer dude Oct 09 '18 at 10:38

1 Answers1

3

add hexadecimalnum[l] = 0; after the while loop. You need to terminate the string

0___________
  • 60,014
  • 4
  • 34
  • 74