0

i'm a beginner in c programing language and when i was train to do some exercices , i saw this

hex[index] = (char)(i + 48);

and

hex[index] = (char)((i-10) + 65);

and i haven't undertood it .

the full code is here: https://codeforwin.org/2015/08/c-program-to-convert-binary-to-hexadecimal-number-system.html.

4
  • 1
    In ASCII, 48 is ‘0’ and 65 is ‘A’. You shouldn’t use those values though - use the characters instead - more readable and more portable. Commented Sep 15, 2019 at 7:01
  • It seems that hex is an array of characters - hence you don't need to typecast with (char) Commented Sep 15, 2019 at 7:07
  • Just a tip, while it can sometimes be useful to see other peoples code the best way to learn something is to do yourself. And considering the use of magic numbers in the code you found, that's not really a good source for learning. If other code at that site is similar, then please continue to search for example code. Commented Sep 15, 2019 at 7:07
  • thank you Paul R but why there is char before this two number.or it's just kind of syntax Commented Sep 15, 2019 at 8:07

1 Answer 1

1
hex[index] = (char)(i + 48);

takes the index i in the range 0 to 9 and converts it into the character '0' to '9', resp. The character code of '0' is 48.

hex[index] = (char)((i-10) + 65);

does the similar thing with the index i in the range 10 to 15 and converts it into the character 'A' to 'F', resp. The character code of 'A' is 65.

This conversion is only true for ASCII and derived character coding which you are using most probably.

<rant> Some people just have learned to stumble in a language and the first thing they do is to set up a web page titling it "C programming for beginners." But due to their really limited knowledge of the language they spread wrong and half-baked statements... Unfortunately you fell into one of these traps. Well, it could bring you to learn more and better because you find the gaps and errors on that web sites. Good luck! </rant>

Both lines should have been written like this, not taking into account other issues with the linked program:

hex[index] = i + '0';

and

hex[index] = i - 10 + 'A';

Or, even better:

char hex[] = "0123456789ABCDEF";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.