I have what I think is an easy problem. For some reason the following code generates the exception, \"String must be exactly one character long\".
int n = 0;
for
Since printable unicode characters can be anywhere in range from 0x0000
to 0xFFFF
, your hexOutput variable can hold more than one character - this is why error is thrown.
Convert.ToChar(string)
would always check length a of string, and if it is not equal to 1 - it would throw. So it would not convert string 0x30
to hexadecimal number, and then to ascii representation, symbol 0
.
Can you elaborate on what you are trying to archieve ?
Convert.ToChar( string s )
, per the documentation requires a single character string, otherwise it throws a FormatException
as you've noted. It is a rough, though more restrictive, equivalent of
public char string2char( string s ) { return s[0] ; }
Your code does the following:
char
is an integral type: its an unsigned 16-bit integral value.What exactly are you trying to accomplish here. For instance, given a charMsg
that consist of 3 characters, 'a', 'b' and 'c', what should happen. A clear problem statement helps us to help you.
Your hexOutput is a string, and I'm assuming charMsg is a character array. Suppose the first element in charMsg is 'p', or hex value 70. The documentation for Convert.ToChar(string) says it'll use just the first character of the string ('7'), but it's wrong. It'll throw this error. You can test this with a static example, like charMsg[n] = Convert.ToChar("70");
. You'll get the same error.
Are you trying to replace characters with hex values? If so, you might try using a StringBuilder object instead of your array assignments.
Convert.ToChar(string) if it is empty string lead this error. instead use cchar()