0

I am relatively new in Java, and attempting to convert user inputs into Hexidecimal. Currently I am attempting to convert it first to Bytes, however I am getting errors regarding one line, Byte getByte = Byte.parseByte(getCharacter);

The overall code can be seen below,

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);

    }
}

I have seen answers however I do not understand how to incorporate stuff like char a = '\uffff' into my program.

Connor
  • 57
  • 1
  • 2
  • 12
  • How do you want to convert user text input to hexadecimal? Do you want to show the ASCII/UTF-8 value of the characters in hexadecimal (`a` -> `0x61`)? Or do they enter a number in decimal that you want to output as hexadecimal (`10` -> `0x0A`)? – Thilo Feb 28 '18 at 15:02
  • https://stackoverflow.com/questions/923863/converting-a-string-to-hexadecimal-in-java – GriffeyDog Feb 28 '18 at 15:02

1 Answers1

1

If you're trying to convert an entire String into hexadecimal, the easiest way would be to do:

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
    }
}

If you absolutely need to take in a char as opposed to a String, I think the easiest solution is to just convert into a String and then into a byte array:

byte[] bytes = new String(ch).getBytes("UTF-8");
Scicrazed
  • 542
  • 6
  • 20