将扫描仪字符转换为字节

问题描述 投票:0回答:1

我在Java中相对较新,并尝试将用户输入转换为十六进制。目前我正在尝试将其首先转换为Bytes,但是我遇到了一行qazxsw poi的错误

整体代码如下所示,

Byte getByte = Byte.parseByte(getCharacter);

我见过import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { // write your code here Scanner scanner = new Scanner(System.in); String name = scanner.next(); String binary = "", hexidecimal = ""; ArrayList<Character> chars = new ArrayList<>(); for(char c : name.toCharArray()) chars.add(c); for(char c : chars) { try { String getCharacter = Character.toString(c); Byte getByte = Byte.parseByte(getCharacter); String stringByte = Byte.toString(getByte); binary.concat(stringByte); } catch (NumberFormatException e) { e.printStackTrace(); } } System.out.println(binary); } } 然而我不明白如何将answers这样的东西加入到我的程序中。

java type-conversion character byte
1个回答
1
投票

如果您尝试将整个String转换为十六进制,最简单的方法是:

char a = '\uffff'

如果您绝对需要接受char而不是String,我认为最简单的解决方案是只转换为String然后转换为字节数组:

public class stringToHex {
    public static void main(String[] args) throws UnsupportedEncodingException { //exception is necessary to convert to a byte array
        String test = "Hello World";
        byte[] bytes = test.getBytes("UTF-8"); //make a byte array out of the string
        System.out.println(DatatypeConverter.printHexBinary(bytes)); //use DatetypeConverter to convert binary to hex
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.