HasKal
HasKal

Reputation: 53

Retrieving the Unicode value of char: Java

I am looking for a way to retrieve the Unicode value for a given char, and if possible store it as an integer. Any inbuilt method for this in Java, or do I have to code my own?

Context

I am building a basic encryption program for fun. What I need is to map each character in the Unicode set to an integer, which I can then manipulate in my encryption formula.

I thought about using ASCII values for char by typecasting the char as an int, but then I read about Unicode online, and realised my mistake.

Any help will be appreciated.

Upvotes: 4

Views: 12633

Answers (1)

AllTooSir
AllTooSir

Reputation: 49372

The Java programming language represents text in sequences of 16-bit code units, using the UTF-16 encoding.

Hence this is enough :

char character='a';
int code = character;
System.out.println(code);

As per JLS 3.10.4

Character literals can only represent UTF-16 code units (§3.1), i.e., they are limited to values from \u0000 to \uffff. Supplementary characters must be represented either as a surrogate pair within a char sequence, or as an integer, depending on the API they are used with.

Upvotes: 3

Related Questions