Ascii кодом символа java

Java – Преобразование символов в ASCII

В этой статье показано, как преобразовать символ в значение ASCII. В Java мы можем привести char к int, чтобы получить значение ASCII.

В Java мы можем привести char к int , чтобы получить значение ASCII char .

char aChar = 'a'; //int ascii = (int) aChar; // explicitly cast, optional, improves readability int ascii = aChar; // implicit cast, auto cast char to int, System.out.println(ascii); // 97

Явный бросок (int)символ является необязательным, если мы присвоим символ целому числу, Java автоматически приведет символ к int .

1. Преобразовать символ в ASCII

Этот пример Java преобразует символ в значение ASCII, и мы можем использовать символ .Точары чтобы вернуть значение ASCII обратно в символ.

package com.mkyong.basic; public class JavaAsciiExample1 < public static void main(String[] args) < // convert char to ASCII char aChar = 'a'; int ascii = aChar; // auto cast char to int System.out.println(ascii); // 97 // convert ASCII to char char[] chars = Character.toChars(ascii); System.out.println(chars); // a char aChar2 = (char) ascii; // or downcast int to char, it works. System.out.println(aChar2); // a >>

В ASCII десятичная дробь от 0 до 31 и 127 представляют материалы, связанные с файлами; печатаемые символы от 32 до 126. Чтобы преобразовать ASCII обратно в символ или строку, мы можем выполнить простую проверку диапазона, чтобы убедиться, что это допустимое значение ASCII.

public static char asciiToChar(final int ascii) < if (ascii < 0 || ascii >= 127) < throw new IllegalArgumentException("Invalid ASCII value!"); >return (char) ascii; >

2. Преобразование строки в ASCII

2.1 Мы можем использовать String.getBytes(стандартные наборы символов. US_ASCII) для преобразования строки в массив байтов |/байт [] и передайте байт в int , чтобы получить значение ASCII.

package com.mkyong.basic; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; public class JavaAsciiExample2 < public static void main(String[] args) < String input = "abcdefg"; byte[] bytes = input.getBytes(StandardCharsets.US_ASCII); // print the first byte System.out.println(bytes[0]); // 97 Listresult = new ArrayList<>(); // convert bytes to ascii for (byte aByte : bytes) < int ascii = (int) aByte; // byte ->int result.add(ascii); > System.out.println(result.toString()); // [97, 98, 99, 100, 101, 102, 103] > > 
97 [97, 98, 99, 100, 101, 102, 103]

2.2 Java 9, есть новый API String.char() для преобразования строки в Входной поток , за которым следует .в штучной упаковке () , и он преобразуется в Поток .

String input = "abcdefg"; List collect = input .chars() // IntStream .boxed() // Stream, ASCII values .collect(Collectors.toList()); // Returns a List collect.forEach(System.out::println); 

2.3 Для преобразования значений ASCII обратно в строку мы можем использовать символ .toString , он принимает целое число (кодовую точку) в качестве аргумента и возвращает строку.

package com.mkyong.basic; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class JavaAsciiExample3 < public static void main(String[] args) < Listascii = Arrays.asList(97, 98, 99, 100, 101, 102, 103); // Java 8 stream String result = ascii.stream() .map(x -> Character.toString(x)) // int -> string .collect(Collectors.joining()); // return a string System.out.println(result); > > 

Рекомендации

Источник

Get the ASCII Value of a Character in Java

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

In this short tutorial, we’ll see how to get the ASCII value of a character in Java.

2. Use Casting

To get the ASCII value of a character, we can simply cast our char as an int:

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

Remember that char in Java can be a Unicode character. So our character must be an ASCII character to be able to get its correct ASCII numeric value.

3. Character Inside a String

If our char is in a String, we can use the charAt() method to retrieve it:

String str = "abc"; char c = str.charAt(0); System.out.println((int) c);

4. Conclusion

In summary, we’ve learned how to get the ASCII value of a character in Java.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

How to get the ASCII value of a character in Java

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

What are ASCII values?

ASCII assigns letters, numbers, characters, and symbols a slot in the 256 available slots in the 8-bit code.

Character ASCII value
a 97
b 98
A 65
B 66

Cast char to int

Cast a character from the char data type to the int data type to give the ASCII value of the character.

Code

In the code below, we assign the character to an int variable to convert it to its ASCII value.

public class Main
public static void main(String[] args)
char ch = 'a';
int as_chi = ch;
System.out.println("ASCII value of " + ch + " is - " + as_chi);
>
>

In the code below, we print the ASCII value of every character in a string by casting it to int .

public class Main
public static void main(String[] args)
String alphabets = "abcdjfre";
for(int i=0;ichar ch = alphabets.charAt(i);
System.out.println("ASCII value of " + ch + " is - " + (int)ch);
>
>
>

Learn in-demand tech skills in half the time

Источник

How to Convert an ASCII Code to char in Java?

ASCII is the abbreviation of “American Standard Code for Information Interchange”. A computer knows the language in numeric form. Therefore, ASCII is used to communicate with computers by exchanging information. All keyboard characters, including all alphabets, numbers, and special characters, comprise a unique ASCII code that the computer understands to process the typed key.

This blog will discuss converting an ASCII code to a character in Java.

How to Convert an ASCII Code to char in Java?

For converting an ASCII code to a character in Java, there are different methods listed below:

Let’s check the functionality of each of these methods with examples.

Method 1: To Convert an ASCII Code to char Using Type Casting

Most programmers utilize Type Casting for converting an ASCII code to char in a Java program as it directly converts one data type to another.

Syntax
The syntax for converting ASCII Code to char in Java using the Type Casting method is given as:

ascii” is the variable that stores a value of data type “int”. The keyword “char” with the parenthesis like “(char)” indicates that the mentioned int type “ascii” variable is typecasted into a character, and the resultant value will be stored in “asciiToChar”.

Let’s check out an example to understand the conversion of ASCII code to char using Type Casting.

Example
Here, we have an integer type variable “ascii” initialized with “69”:

Now, we will convert the created variable to a character using Type Casting:

Lastly, we will print the resultant character “ascii”:

The output indicates that the ASCII code “69” is converted to “E” char:

Let’s check some other methods to convert the ASCII code to char in Java.

Method 2: To Convert an ASCII Code to char Using toString()

The Java wrapper class named “Character” also offers a “toString()” method, which allows us to convert an ASCII code to the string representing the character’s value.

Here, “ascii” is an “int” type data variable containing ASCII code that will be converted to a string referring to the corresponding character.

Example
In this example, we have an ASCII value “75” stored in “ascii”:

We will call the “Character.toString()” method by passing the created character as a parameter and then store the returned value in “asciiToChar” String type variable. Now the question is why it is a String type variable, not a character type? Because the toString() method will always return a string:

Lastly, execute the “System.out.println()” method to print out the required value:

As you can see, the given program successfully converted “75” ASCII code to the “K” character:

We have one more method to perform the same operation. So, move to the next section!

Method 3: To Convert an ASCII Code to char Using toChars()

The “toChars()” method of the Character wrapper class can also be utilized to convert an ASCII code to char in a Java program. It returns the output as an array of characters.

Here, “ascii” is an integer type variable having ASCII code that is passed to the “Character.toChars()” method. This method will return a character array.

Example
Firstly, we will create a variable named “ascii” having “116” as ASCII code:

Then, we will call the “Character.toChars()” method, pass “ascii” as an argument, and store the returned char array in “asciiToChar”:

Lastly, we will print the output on the console:

System . out . print ( «Ascii » + ascii + » is a value of Character: » ) ;
System . out . println ( asciiToChar ) ;

We presented the easiest methods to convert ASCII code to char in Java.

Conclusion

To convert ASCII code to a character, you can use different methods such as Type Casting, toString() method, and toChars() method of the Character class. The toString() method will return a character as a String, while the toChars() method returns the array of characters. Type Casting is the most common and easy method to convert an ASCII code to a character, as it directly typecasts the ASCII code to char. This blog discussed the methods used to convert an ASCII code to char in Java.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

Читайте также:  Cloning objects in javascript
Оцените статью