Char to Int in C++

Hello,
How can I fix this code? I want to send number to a method and get Char.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>


char ConvertTo(int a)
{
	if (a <= 9 && a >= 0)
		return (char)a;
}


int main()
{
	
	int a = 5;
	char b = ConvertTo(a);
	 std::cout<<ConvertTo(a);

	return 0;
}
Last edited on
problem with that is that int is 32bit value (at least on windows) and char is 8 bits

what you want is std::byte maybe

or maybe use HIWORD/LOWORD macros first and then you have 8bit value convertable to char.
for example:

char a = reinterpret_cast<char>(LOWORD(param));

assuming param is 16 bit value, that is short
Last edited on
1
2
3
4
char ConvertTo(int a)
{
   return a + '0';
}
@lastchance
how will that work if int contains a number grater than 255 ?
not attacking, just would like to know..
how will that work if int contains a number grater than 255 ?
not attacking, just would like to know..


It won't work. So don't do it! (Which was, presumably, the implication of the OP's original 'if' test.)

What would you like it to do if int contains a number greater than 255 - '0'?
Last edited on
Topic archived. No new replies allowed.