Java에서 문자를 ASCII 숫자 값으로 변환
나는 String name = "admin";
그때String char = name.substring(0,1); //char="a"
를 char
ASCII 값 (97) 으로 변환하고 싶습니다 .Java에서 어떻게 할 수 있습니까?
매우 간단합니다. 그냥 캐스팅 char
int로서 int
.
char character = 'a';
int ascii = (int) character;
귀하의 경우 먼저 문자열에서 특정 문자를 가져 와서 캐스팅해야합니다.
char character = name.charAt(0); // This gives the character 'a'
int ascii = (int) character; // ascii is now 97.
캐스트는 명시 적으로 필요하지 않지만 가독성을 향상시킵니다.
int ascii = character; // Even this will do the trick.
다른 접근법
String s = "admin";
byte[] bytes = s.getBytes("US-ASCII");
bytes[0]
는 전체 배열에서 다른 문자의 ASCII를 나타냅니다.
이 대신에 :
String char = name.substring(0,1); //char="a"
이 charAt()
방법을 사용해야합니다 .
char c = name.charAt(0); // c='a'
int ascii = (int)c;
전체 문자열을 연결된 ASCII 값으로 변환하려면 다음을 사용할 수 있습니다.
String str = "abc"; // or anything else
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray())
sb.append((int)c);
BigInteger mInt = new BigInteger(sb.toString());
System.out.println(mInt);
여기서 출력으로 979899가 표시됩니다.
에 신용 이 .
방금 다른 사람들에게 편리하도록 여기에 복사했습니다.
Java 문자가 ASCII 문자가 아니기 때문에이를 수행하는 방법을 보여주기 위해 제시된 몇 가지 대답은 모두 잘못되었습니다. Java는 유니 코드 문자의 멀티 바이트 인코딩을 사용합니다. 유니 코드 문자 집합은 ASCII의 슈퍼 집합입니다. 따라서 Java 문자열에 ASCII에 속하지 않는 문자가있을 수 있습니다. 이러한 문자에는 ASCII 숫자 값이 없으므로 Java 문자의 ASCII 숫자 값을 얻는 방법을 묻는 것은 대답 할 수 없습니다.
그런데 왜 어쨌든 이것을하고 싶습니까? 당신은 그 가치로 무엇을 할 것입니까?
Java 문자열을 ASCII 문자열로 변환 할 수 있도록 숫자 값을 원한다면 실제 질문은 "Java 문자열을 ASCII로 인코딩하는 방법"입니다. 이를 위해 object를 사용하십시오 StandardCharsets.US_ASCII
.
char을 int로 변환하십시오.
String name = "admin";
int ascii = name.toCharArray()[0];
또한 :
int ascii = name.charAt(0);
그냥 문자를 int로 캐스팅하십시오.
char character = 'a';
int number = (int) character;
값은 number
97입니다.
간단하고 원하는 문자를 가져 와서 int로 변환하십시오.
String name = "admin";
int ascii = name.charAt(0);
나는 이것이 이미 여러 형태로 대답되었다는 것을 알고 있지만 여기에 모든 문자를 살펴볼 수있는 코드가 있습니다.
클래스로 시작한 코드는 다음과 같습니다.
public class CheckChValue { // Class name
public static void main(String[] args) { // class main
String name = "admin"; // String to check it's value
int nameLenght = name.length(); // length of the string used for the loop
for(int i = 0; i < nameLenght ; i++){ // while counting characters if less than the length add one
char character = name.charAt(i); // start on the first character
int ascii = (int) character; //convert the first character
System.out.println(character+" = "+ ascii); // print the character and it's value in ascii
}
}
}
String str = "abc"; // or anything else
// Stores strings of integer representations in sequence
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray())
sb.append((int)c);
// store ascii integer string array in large integer
BigInteger mInt = new BigInteger(sb.toString());
System.out.println(mInt);
String name = "admin";
char[] ch = name.toString().toCharArray(); //it will read and store each character of String and store into char[].
for(int i=0; i<ch.length; i++)
{
System.out.println(ch[i]+
"-->"+
(int)ch[i]); //this will print both character and its value
}
public class Ascii {
public static void main(String [] args){
String a=args[0];
char [] z=a.toCharArray();
for(int i=0;i<z.length;i++){
System.out.println((int)z[i]);
}
}
}
@Raedwald가 지적했듯이 Java의 유니 코드는 ASCII 값을 얻기 위해 모든 문자를 처리하지 않습니다. 올바른 방법 (Java 1.7 이상) 은 다음과 같습니다.
byte[] asciiBytes = "MyAscii".getBytes(StandardCharsets.US_ASCII);
String asciiString = new String(asciiBytes);
//asciiString = Arrays.toString(asciiBytes)
이를위한 쉬운 방법은 다음과 같습니다.
int character = 'a';
"문자"를 인쇄하면 97이됩니다.
또는 Java 1.8에서 시작하는 1 문자 또는 문자열에 Stream API를 사용할 수 있습니다.
public class ASCIIConversion {
public static void main(String[] args) {
String text = "adskjfhqewrilfgherqifvehwqfjklsdbnf";
text.chars()
.forEach(System.out::println);
}
}
이 코드로 ASCII 번호를 확인할 수 있습니다.
String name = "admin";
char a1 = a.charAt(0);
int a2 = a1;
System.out.println("The number is : "+a2); // the value is 97
내가 틀렸다면 사과드립니다.
문자열에있는 모든 문자의 ASCII 값을 원하는 경우 이것을 사용할 수 있습니다 :
String a ="asdasd";
int count =0;
for(int i : a.toCharArray())
count+=i;
그리고 String에서 단일 문자의 ASCII를 원하면 다음을 수행 할 수 있습니다.
(int)a.charAt(index);
나는 같은 일을 시도했지만 가장 쉽고 쉬운 해결책은 charAt을 사용하고 인덱스에 액세스하는 것이 [128] 크기의 정수 배열을 만들어야합니다.
String name = "admin";
int ascii = name.charAt(0);
int[] letters = new int[128]; //this will allocate space with 128byte size.
letters[ascii]++; //increments the value of 97 to 1;
System.out.println("Output:" + ascii); //Outputs 97
System.out.println("Output:" + letters[ascii]); //Outputs 1 if you debug you'll see 97th index value will be 1.
완전한 문자열의 ASCII 값을 표시하려면이 작업을 수행해야합니다.
String name = "admin";
char[] val = name.toCharArray();
for(char b: val) {
int c = b;
System.out.println("Ascii value of " + b + " is: " + c);
}
이 경우 출력은 다음과 같습니다. Ascii 값 a는 : 97 Ascii 값 d는 : 100 Ascii 값 m은 : 109 Ascii 값 i는 : 105 Ascii 값 n은 : 110
이를 수행하는 쉬운 방법은 다음과 같습니다.
전체 문자열을 ASCII로 :
public class ConvertToAscii{
public static void main(String args[]){
String abc = "admin";
int []arr = new int[abc.length()];
System.out.println("THe asscii value of each character is: ");
for(int i=0;i<arr.length;i++){
arr[i] = abc.charAt(i); // assign the integer value of character i.e ascii
System.out.print(" "+arr[i]);
}
}
}
출력은 다음과 같습니다.
THe asscii value of each character is: 97 100 109 105 110
여기
abc.charAt(i)
에 String 배열의 단일 문자를 제공합니다. 각 문자를 정수 유형에 할당하면 컴파일러는 다음과 같이 유형 변환을 수행합니다.
arr[i] = (int) character // Here, every individual character is coverted in ascii value
그러나 단일 문자의 경우 :
String name = admin; asciiValue = (int) name.charAt(0);// for character 'a' System.out.println(asciiValue);
Java 9 => String.chars () 사용
String input = "stackoverflow";
System.out.println(input.chars().boxed().collect(Collectors.toList()));
출력-[115, 116, 97, 99, 107, 111, 118, 101, 114, 102, 108, 111, 119]
이를 위해 우리는 즉시 String classe를 사용할 수 있습니다.
input.codePointAt(index);
I would like to give one more suggestion as to get whole of string converted to corresponding ascii codes, using java 8 for example, "abcde" to "979899100101".
String input = "abcde";
System.out.println(
input.codePoints()
.mapToObj((t) -> "" + t)
.collect(joining()));
참고URL : https://stackoverflow.com/questions/16458564/convert-character-to-ascii-numeric-value-in-java
'development' 카테고리의 다른 글
교리-준비된 진술뿐만 아니라 실제 SQL을 인쇄하는 방법? (0) | 2020.06.11 |
---|---|
mysql에서 하나의 셀 데이터 변경 (0) | 2020.06.11 |
MySQL에서이 연산자 <=>는 무엇입니까? (0) | 2020.06.11 |
CodeIgniter activerecord, 마지막 삽입 ID를 검색 하시겠습니까? (0) | 2020.06.11 |
Docker-compose : npm 설치가 성공한 후 볼륨에 node_modules가 없습니다. (0) | 2020.06.11 |