[英]How to convert a character into an integer in Java?
I am a beginner at Java, trying to figure out how to convert characters from a text file into integers.我是 Java 的初学者,试图弄清楚如何将文本文件中的字符转换为整数。 In the process, I wrote a program which generates a text file showing what characters are generated by what integers.
在这个过程中,我编写了一个程序,它生成一个文本文件,显示哪些字符由哪些整数生成。
package numberchars;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileReader;
import java.lang.Character;
public class Numberchars {
public static void main(String[] args) throws IOException {
FileWriter outputStream = new FileWriter("NumberChars.txt");
//Write to the output file the char corresponding to the decimal
// from 1 to 255
int counter = 1;
while (counter <256)
{
outputStream.write(counter);
outputStream.flush();
counter++;
}
outputStream.close();
This generated NumberChars.txt, which had all the numbers, all the letters both upper and lower case, surrounded at each end by other symbols and glyphs.这生成了 NumberChars.txt,其中包含所有数字、所有大写和小写字母,每一端都被其他符号和字形包围。
Then I tried to read this file and convert its characters back into integers:然后我尝试读取此文件并将其字符转换回整数:
FileReader inputStream = new FileReader("NumberChars.txt");
FileWriter outputStream2 = new FileWriter ("CharNumbers.txt");
int c;
while ((c = inputStream.read()) != -1)
{
outputStream2.write(Character.getNumericValue(c));
outputStream2.flush();
}
}
}
The resulting file, CharNumbers.txt
, began with the same glyphs as NumberChars.txt but then was blank.生成的文件
CharNumbers.txt
以与 NumberChars.txt 相同的字形开头,但随后为空白。 Opening the files in MS Word, I found NumberChars had 248 characters (including 5 spaces) and CharNumbers had 173 (including 8 spaces).在 MS Word 中打开文件,我发现 NumberChars 有 248 个字符(包括 5 个空格),而 CharNumbers 有 173 个(包括 8 个空格)。
So why didn't the Character.getNumericValue(c)
result in an integer written to CharNumbers.txt?那么为什么
Character.getNumericValue(c)
产生一个整数写入 CharNumbers.txt 呢? And given that it didn't, why at least didn't it write an exact copy of NumberChars.txt?鉴于它没有,为什么至少它不写一个 NumberChars.txt 的精确副本? Any help much appreciated.
非常感谢任何帮助。
Character.getNumericValue
doesn't do what you think it does. Character.getNumericValue
不会做您认为的那样。 If you read the Javadoc :如果您阅读Javadoc :
Returns the
int
value that the specified character (Unicode code point) represents.返回指定字符(Unicode 代码点)表示的
int
值。 For example, the character'\Ⅼ'
(the Roman numeral fifty) will return an int with a value of50
.例如,字符
'\Ⅼ'
(罗马数字 50)将返回一个值为50
的 int 。
On error it returns -1
(which looks like 0xFF_FF_FF_FF
in 2s complement).出错时它返回
-1
(在 2s 补码中看起来像0xFF_FF_FF_FF
)。
Most characters don't have such a "numeric value," so you write the ints out, each padded to 2 bytes (more on that later), read them back in the same way, and then start writing a whole lot of 0xFFFF
( -1
truncated to 2 bytes) courtesy of a misplaced Character.getNumericValue
.大多数字符没有这样的“数值”,所以你写出整数,每个填充到 2 个字节(稍后会详细介绍),以相同的方式读回它们,然后开始写入大量
0xFFFF
( -1
截断为 2 个字节)由放错位置的Character.getNumericValue
。 I'm not sure what MS Word is doing, but it's probably getting confused what the encoding of your file is and glomming all those bytes into 0xFF_FF_FF_FF
(because the high bits of each byte are set) and treating that as one character.我不知道微软Word正在做,但它可能是越来越糊涂你的文件的编码是什么,glomming所有这些字节到
0xFF_FF_FF_FF
(因为每个字节的最高位设置)和治疗,作为一个字符。 (Use a text editor more suited to this kind of stuff like Notepad++, btw.) If you were to measure your file's size on disk in bytes it will probably still be 256 chars * 2 bytes/chars = 512 bytes
. (使用更适合这类东西的文本编辑器,例如 Notepad++,顺便说一句。)如果您要以字节为单位测量磁盘上文件的大小,它可能仍然是
256 chars * 2 bytes/chars = 512 bytes
。
I'm not sure what you meant to do here, so I'll note that InputStreamReader
and OutputStreamWriter
work on a (Unicode) character basis, with an encoder that defaults to the system one.我不确定您在这里要做什么,所以我会注意到
InputStreamReader
和OutputStreamWriter
在 (Unicode) 字符基础上工作,编码器默认为系统编码器。 That's why your ints are padded/truncated to 2 bytes.这就是为什么您的整数被填充/截断为 2 个字节的原因。 If you wanted pure byte IO, use
FileInputStream
/ FileOutputStream
.如果您想要纯字节 IO,请使用
FileInputStream
/ FileOutputStream
。 If you wanted to read and write the int
s as String
s, you need to use FileWriter
/ FileReader
, but not like you did.如果您想将
int
s 读写为String
s,则需要使用FileWriter
/ FileReader
,但不像您那样。
// Just bytes
// This is a try-with-resources. It executes the code with the decls in it
// but is also like an implicit finally block that calls `close()` on each resource.
try(FileOutputStream fos = new FileOutputStream("bytes.bin")) {
for(int b = 0; b < 256; b++) { // Bytes are signed so we use int.
// This takes an int and truncates it for the lowest byte
fos.write(b);
// Can also fill a byte[] and dump it all at once with overloaded write.
}
}
byte[] bytes = new bytes[256];
try(FileInputStream fis = new FileInputStream("bytes.bin")) {
// Reads up to bytes.length bytes into bytes
fis.read(bytes);
}
// Foreach loop. If you don't know what this does, I think you can figure out from the name.
for(byte b : bytes) {
System.out.println(b);
}
// As Strings
try(FileWriter fw = new FileWriter("strings.txt")) {
for(int i = 0; i < 256; i++) {
// You need a delimiter lest you not be able to tell 12 from 1,2 when you read
// Uses system default encoding
fw.write(Integer.toString(i) + "\n");
}
}
byte[] bytes = new byte[256];
try(
FileReader fr = new FileReader("strings.txt");
// FileReaders can't do stuff like "read one line to String" so we wrap it
BufferedReader br = new BufferedReader(fr);
) {
for(int i = 0; i < 256; i++) {
bytes[i] = Byte.valueOf(br.readLine());
}
}
for(byte b : bytes) {
System.out.println(b);
}
public class MyCLAss {
public static void main(String[] args)
{
char x='b';
System.out.println(+x);//just by witting a plus symbol before the variable you can find it's ascii value....it will give 98.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.