0

How to convert integer to char and vice versa in "Dynamic C".

Use VB.NET as bellow:

Dim i As Integer
Dim c As Char

' Integer to Character
i = 302
c = ChrW(302)
Debug.Print(c)  'Result: Į

' Character to Integer
Dim j As Integer
j = AscW(c)
Debug.Print(CStr(j))  ' Result: 302

Thanks

Javanese Girl
  • 337
  • 2
  • 6
  • 14
  • 1
    Is your VB an example of what you want to be done, but using "Dynamic C"? Since chars are just really small integers in C, you don't need to convert them (although they typically aren't big enough to hold the value 302). – Scott Hunter Jan 07 '12 at 17:40

3 Answers3

1

Since both int and char are integer types, you can simply assign an appropriately-valued integer to a char and vice versa:

int i = 65; // 'A'
char c = 'B'; // 66;
int cAsInt = (int)c; // 66 = 'B'
char iAsChar = (char)i; // 'A' = "65"
  • then what would happen with i=302? – Jim Rhodes Jan 07 '12 at 17:41
  • As far as I know, i=302 is not a valid character code... and otherwise, it would let iAsChar be (302 modulo 256). –  Jan 07 '12 at 17:42
  • @JimRhodes, you can't fit 302 into a char. It s value would be truncated so that it fits. – Jack Edmonds Jan 07 '12 at 17:43
  • @JackEdmonds - a Char in VB.NET is 16 bits. It is not the same as a char in C. – Jim Rhodes Jan 07 '12 at 17:46
  • I've heard about Unicode, but char is always one byte (the C standard requires it; we're already talking about C and not VB which was only a sample), which is ubviously not a (say) 2-byte character. –  Jan 07 '12 at 17:49
  • @H2CO3 - But the OP explicitly uses 302 which in Unicode is an upper case I with a tail – Jim Rhodes Jan 07 '12 at 17:57
  • @all, I want to use unicode character as the delimiter of the following protocol. STX - ADDRS - COMMAND - DATA - ETX - CRC. I want to replace the STX and ETX use unicode character because after the DATA is encrypted, the DATA contained ASCII Control Character (STX and ETX). To prevent it happening I want use delimiter with a value of more than 255. Eg: STX=302 and ETX=303. I can do it in VB.NET use ChrW and AscW but difficulty in dynamic c. Any ideas? thanks – Javanese Girl Jan 07 '12 at 18:03
  • 1
    @H2CO3 why the casts? there are implicit conversions between int to char and char to int, the casts are useless. – ouah Jan 07 '12 at 18:28
  • @Jim, You are right, VB.NET support for 2 bytes Char but not same with C only 1 byte Char. I'm used WORD, same with 2 Char. All, Thank You. – Javanese Girl Jan 08 '12 at 16:29
1

If you want to parse a character such that '1' becomes the integer 1, you can use itoa and atoi.

If you want to convert between the the ascii values and their characters, that's even easier. Simply cast the int to a char or the char to an int.

Jack Edmonds
  • 31,931
  • 18
  • 65
  • 77
0

Why dont you use an other type like uint16_t that can be used for UCS2 ? I mean char is used for ascii and extended 0-255 ~ uint8_t, if you need more dont use char.

uint16_t c=302;
cendar
  • 34
  • 3