java convert String of integers into possible combination of ASCII characters - java

Say that I have
String input = "Programming", result="\0";
int temp;
for (int i=0;i<input.length();++i) {
temp = input.charAt(i);
result += temp;
}
result would be 8011411110311497109109105110103. I know that
P = 80
r = 114
o = 111
g = 103
r = 114
a = 97
m = 109
m = 109
i = 105
n = 110
g = 103
Out of curiosity, is it possible, in easy way, to reverse the process?

what you would have to do is assume that Each number lies between either 'A' to 'Z', (65 to 90) or 'a' to 'z' (97 to 122)
get the first 2 digits via a call to substring()
check if those lie within the above bounds by converting to a numeric type
if they do then continue with the loop
else get the third digit and check that
it would be much simpler if you could have it be padded to three digits so you would know that every three digits formed an ASCII letter
code that works only if it is letters:
public static void main(String[] args) {
String toConvert= "8011411110311497109109105110103";
String result="";
while(toConvert.length()>0){
String digits=toConvert.substring(0, 2);
int num=Integer.valueOf(digits);
if(('A'<=num&&num<='Z')||('a'<=num&&num<='z')){
toConvert=toConvert.substring(2);
}
else{
digits=toConvert.substring(0, 3);
num=Integer.valueOf(digits);
toConvert=toConvert.substring(3);
}
String letter = String.valueOf((char) num);
result+=letter;
}
System.out.println(result);
}
note if you change the test to num>25 , then it will correctly work for all ASCII values from 26 up: for values 26 to 99, it will interpret them as having 2 digits correctly, for values from 100 to 255 it will only look at the first 2 digits, so they will be seen as 10-25, and will be interpreted as 3 digits long

Related

Extracting numbers from a string while keeping spaces

Given a string, I want to extract the numbers and keep a spacing between them.
The procedure for this generally involves removing all spacing so that 12 3 becomes 123 which I'm avoiding.
For example if the input is 17/(2 + 3)-13 I want 17 2 3 13.
I also have methods that extract the operators and parenthesis in between them but I can't separate the numbers greater than 9.
Here's my attempt which produces out of bounds exceptions
public static void partition(){
String word = "123 -asdfqwerty- 45";
String kajigger = "";
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if(Character.isDigit(c)){
int j = i;
while(Character.isDigit(word.charAt(j))){
kajigger += word.charAt(j);
j++;
}
}
}
System.out.println(kajigger);
}
In this example I wanted the output 123 45
The general idea is converting from infix to postfix by moving all numbers the the left and operators to the right.
You go by this way :
replace all multiple following (+) chars which are non-digits (\D) by a single space (" ")
so \D+ changes 7/(2 + 3)-13 into 7 2 3 13
String str = "17/(2 + 3)-13";
str = str.replaceAll("\\D+", " ");
System.out.println(str); // 17 2 3 13
Regex demo

binary to hexa decimal without predefined method (JAVA)

I'm looking for a method that converts binary numbers to hexa decimals (JAVA). Problem is that it can't be done with a predefined method and I just don't know how to do it. I've tried a few things but it throws me off that hexa decimals include chars.
thanks in advance!
It's really a crappy question. You should explain what you have come up with and show the code you've tried so far.
So here's a binary number:
0101111010110010
Split it into groups of four bits (a bit is a binary digit, i.e. 1 or 0):
0101 1110 1011 0010
Now the funny thing is that each group of four bits has a maximum value of....
1111 = 8 + 4 + 2 + 1 = 15
Does that ring a bell? Here are the 'digits' in hexadecimal:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A, B, C, D, E, F
What's the maximum value of a single hexadecimal digit?
15
So this means you can simply translate each group of four bits into a hexadecimal digit:
0101 1110 1011 0010
4+1 8+4+2 8+2+1 2
5 14 11 2
5 E B 2
5EB2
For your requirement first of all you have to convert binary no into decimal and then into hexadecimal. So please try this program it works as per your requirement :
import java.util.Scanner;
public class BinaryToHexa
{
public static void main(String args[])
{
int binnum, rem;
String hexdecnum="";
int decnum=0;
char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
Scanner scan = new Scanner(System.in);
System.out.print("Enter Binary Number : ");
binnum = scan.nextInt();
// converting the number in decimal format
int i=0;
while(binnum>0)
{
rem = binnum%10;
binnum=binnum/10;
decnum = decnum + (int)(rem*Math.pow(2,i));
i++;
}
// converting the number in hexadecimal format
while(decnum>0)
{
rem = decnum%16;
hexdecnum = hex[rem] + hexdecnum;
decnum = decnum/16;
}
System.out.print("Equivalent Hexadecimal Value is :\n");
System.out.print(hexdecnum);
}
}
If you have any doubt please let me know.
Thanks...
What is the exact issue or problem here?
Use Integer.toHexString(num) to convert
Try this function from my library out. You do not do any calculation with this function. Only string compare, and you can convert as much binary to hexadecimal as you like. As long as the limitation on how long a string can be.
public static String binhexZ(String input)
{
String map = "0000,0,0001,1,0010,2,0011,3,0100,4,0101,5,0110,6,0111,7,1000,8,1001,9,1010,A,1011,B,1100,C,1101,D,1110,E,1111,F";
String output = "";
int i = 0;
while (input.length() % 4 != 0){
input = "0" + input;
}
while (i < input.length()){
output += map.charAt(map.indexOf(input.substring(i, i + 4)) + 5);
i = i + 4;
}
output = output.replaceAll("^0+", "");
output = output.length() < 1? "0" : output;
return output;
}

How can I split binary into 4 bytes sections?

I have a char holding different characters, and I would like to print the binary value of these into two 4 bytes sections. I am adding a 1 at the beginning so that they would be 4 each.
System.out.println(1 + Integer.toString(mychar[i],2));
I am using a for loop to go through the different characters and create a table. By doing this I can get the binary value plus the one. But i don't know how to separate it into two 4 bytes.
Lets assume that mychar[i] holds the String bryan. The output should be the following.
b 1110 0010
r 1111 0010
y 1111 1001
a 1110 0001
n 1110 1110
My personal favorite for zero-padding a small number (that is, a byte, a short etc) when converted to binary is:
String binaryRep = Integer.toBinaryString( 0x100 | mychar[i] & 0xff ).substring(1);
The & makes sure that no more than 8 bits are taken from mychar[i]
The 0x100 | part sets the 9th bit. This means all the zeros in the rightmost 8 bits will be represented in the result, which will be exactly 9 characters long.
Then taking the substring from 1 makes sure we take just the 8.
Of course, the above assumes a character that fits into 8 bits. If you try a Chinese or Arabic character it will basically just give you its rightmost 8 bits.
Whatever method you use for producing 8 zero-padded bits, you'll need to add the space in the middle. For my method above, we can make this modification:
public static String eightBitCharToBinary( char c ) {
String charAsNineBits = Integer.toBinaryString( 0x100 | c & 0xff );
return charAsNineBits.substring(1,5) + " " + charAsNineBits.substring(5,9);
}
Which does the same as above, but instead of just taking one substring, takes two substrings and puts a space in the middle.
I've used this answer to come to a solution:
private static String toBinaryRepresentation(String name) {
// 11 is size of "0000 0000\r\n
StringBuilder sb = new StringBuilder(name.length() * 11);
for (int i = 0; i < name.length(); i++) {
String binRep = toBinaryRepresentation(name.charAt(i));
sb.append(String.format("%s%n", binRep));
}
return sb.toString();
}
private static String toBinaryRepresentation(char c) {
if (c > 0xFF) {
throw new IllegalArgumentException("Character value too high to print");
}
int highNibble = (c >> 4) & 0xF;
String highBinaryDigits = String.format("%4s", Integer.toBinaryString(highNibble)).replace(' ', '0');
int lowNibble = c & 0xF;
String lowBinaryDigits = String.format("%4s", Integer.toBinaryString(lowNibble)).replace(' ', '0');
return String.format("%s %s", highBinaryDigits, lowBinaryDigits);
}
Which you can use by calling the function like this:
String name = "brian";
System.out.print(toBinaryRepresentation(name));
This prints:
0110 0010
0111 0010
0110 1001
0110 0001
0110 1110
So this first separates the high and low nibble and then prints the value using precisely 4 bits, even if they are zero.
public static void main(String []args){
String [] mychar = {"bryan"};
int len = mychar.length;
// iterate over each mychar element
for(int i =0; i< len ; i++){
// get the first string from array
String s = mychar[i];
int length = s.length();
//iterate over the string
for(int j =0; j< length ; j++){
char ch = s.charAt(j);
String str = Integer.toBinaryString(ch);
// print each char
System.out.print(ch+" : ");
System.out.println(str.substring(0,4)+" "+str.substring(3) );
}
}
}
char c = 'b';
String binaryString =Integer.toBinaryString(c);
System.out.println("1" + binaryString.substring(0, 3) + " " + binaryString.substring(3));

How can an int be declared with ' ' and why is '2' == 50?

Question is: What gets displayed in console?
And I really have some problems with understanding.
Here is the code:
public static void felda(){
char[] felda = {'2',0x31,48};
for (int i = 0; i< felda.length; i++){
System.out.println(" : " + felda[i]);
}
System.out.println();
}
public static void feldb(){
int[] feldb = {'2',0x31,48};
for (int i = 0; i< feldb.length; i++){
System.out.println(" : " + feldb[i]);
}
System.out.println();
}
public static void feldc(){
int [] feldc = {'2',0x31,48};
for (int i = 0; i< feldc.length; i++){
System.out.println(" : " + (char) feldc[i]);
}
System.out.println();
}
So if I run in the Solution is:
: 2
: 1
: 0
: 50
: 49
: 48
: 2
: 1
: 0
So I don't understand how it is even possible to have an int definded with ' '.
And I find it very confusing how int feldb = '2' results in being 50 and int feldb=0x31 results in being 49.. dam this is all so confusing. I hope someone can enlighten me.
Edit: Why is char feldc = 48; resulting in being 0?
In Java, a char represents a Unicode character. But it's also in fact an unsigned integer, on 2 bytes, which can go from 0 to 216 - 1.
So,
char c = '2';
initializes c with the character '2'. And the numeric value of the character '2', in Unicode, is 50.
So, if you print it as a character, '2' will be printed. If you print it as a numeric value (as an int, using int c = '2'), 50 will be printed.
When doing
char feldc = 48;
you initialize feldc with the character whose numeric Unicode value is 48, and that character is the character '0'. It's thus equivalent to
char feldc = '0';
0x31 is a number written as an hexadecimal literal (that's what the 0xprefix means). When you write 31, the value is in decimal. It's equal to 1 * 100 + 3 * 101.
In hexadecimal, the base is 16 rather than 10. So 0x31 is equal to 1 * 160 + 3 * 161, which is equal to 49.
50 is the ASCII value of the '2' character. Defined like that its not the number 2.. its giving the ASCII value of a character. See this ASCII table and find the '2' char
http://ascii.cl/index.htm?content=mobile

Integer to two digits hex in Java

I need to change a integer value into 2-digit hex value in Java.Is there any way for this.
Thanks
My biggest number will be 63 and smallest will be 0.
I want a leading zero for small values.
String.format("%02X", value);
If you use X instead of x as suggested by aristar, then you don't need to use .toUpperCase().
Integer.toHexString(42);
Javadoc: http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#toHexString(int)
Note that this may give you more than 2 digits, however! (An Integer is 4 bytes, so you could potentially get back 8 characters.)
Here's a bit of a hack to get your padding, as long as you are absolutely sure that you're only dealing with single-byte values (255 or less):
Integer.toHexString(0x100 | 42).substring(1)
Many more (and better) solutions at Left padding integers (non-decimal format) with zeros in Java.
String.format("%02X", (0xFF & value));
Use Integer.toHexString(). Dont forget to pad with a leading zero if you only end up with one digit. If your integer is greater than 255 you'll get more than 2 digits.
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(myInt));
if (sb.length() < 2) {
sb.insert(0, '0'); // pad with leading zero if needed
}
String hex = sb.toString();
If you just need to print them try this:
for(int a = 0; a < 255; a++){
if( a % 16 == 0){
System.out.println();
}
System.out.printf("%02x ", a);
}
i use this to get a string representing the equivalent hex value of an integer separated by space for every byte
EX : hex val of 260 in 4 bytes = 00 00 01 04
public static String getHexValString(Integer val, int bytePercision){
StringBuilder sb = new StringBuilder();
sb.append(Integer.toHexString(val));
while(sb.length() < bytePercision*2){
sb.insert(0,'0');// pad with leading zero
}
int l = sb.length(); // total string length before spaces
int r = l/2; //num of rquired iterations
for (int i=1; i < r; i++){
int x = l-(2*i); //space postion
sb.insert(x, ' ');
}
return sb.toString().toUpperCase();
}
public static void main(String []args){
System.out.println("hex val of 260 in 4 bytes = " + getHexValString(260,4));
}
According to GabrielOshiro, If you want format integer to length 8, try this
String.format("0x%08X", 20) //print 0x00000014

Categories