Advertisement
emesten

Untitled

Jun 8th, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4.  
  5. public static String fillWithZeros(String string) {
  6. if (string.length() == 8)
  7. return string;
  8. else
  9. return fillWithZeros("0"+string);
  10. }
  11.  
  12. public static void main(String[] args) {
  13. Scanner in = new Scanner(System.in);
  14. System.out.println("Please type 1 for string->binaryString or 2 for binaryString->string");
  15. int type;
  16. do {
  17. type = in.nextInt();
  18. } while (!(type == 1 || type == 2));
  19.  
  20. String chain;
  21. if (type == 1) {
  22. System.out.println("Please type in your string to convert");
  23. in.nextLine();
  24. chain = in.nextLine();
  25. String output = "";
  26. for (char x : chain.toCharArray()) {
  27. String temp = Integer.toBinaryString((int) x);
  28. temp = fillWithZeros(temp);
  29. output += temp;
  30. }
  31. System.out.println("Converted string->binaryString: "+output);
  32. }
  33. else {
  34. System.out.println("Please type in your binaryString to convert");
  35. in.nextLine();
  36. chain = in.nextLine();
  37. String[] string = chain.split("");
  38. String current = "";
  39. String output = "";
  40. for (int i = 0; i < string.length; i++) {
  41. if (i%8 == 0 && i != 0) {
  42. int a = Integer.parseInt(current, 2);
  43. output += (char) a;
  44. current = "";
  45. }
  46. current += string[i];
  47. }
  48. int a = Integer.parseInt(current, 2);
  49. output += (char) a;
  50. System.out.println(output);
  51. }
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement