I want to make a code which has function of changing binary to decimal.
So i made a public long tonum()
and tried to return on Main method.
but there is anything shown on screen. Where is the problem?
Plz give me some hints.
public class Bitmap {
byte[] byteArr; //byte array for saving 0 or 1
char[] charArr; //char array for casting from string to byte array
public static void main(String[] args) throws Exception {
Bitmap test1 = new Bitmap("100110");
test1.tonum();
}
public Bitmap(String val) throws Exception {
byteArr = new byte[val.length()]; //To make the array length of Bitmap should e same as that of string
charArr = val.toCharArray(); //casting from string to char
for(int i = 0; i < charArr.length; i++) {
if (charArr[i] == '0')
byteArr[i] = 0;
else if (charArr[i] == '1')
byteArr[i] = 1;
else throw new Exception("Bitmap are should be sequences of zeros and ones!");
}
}
public long tonum() {
int temp = 0;
String str = "";
String str2 = "";
for (int i = 0; i < this.byteArr.length; i++){
temp = this.byteArr[i];
str = Integer.toString(temp);
str2 = str2 + str;
}
long decimal = (long)Integer.parseInt(str2,10);
System.out.println(str2);
return decimal;
}
}
long decimal = (long)Integer.parseInt(str2,10);
That doesn't change binary to decimal. It changes decimal to binary. And you don't have decimal in the first place, you have a string or presentation of binary. Try a radix of 2. But why you have both a char array and a byte array when all you do is deconstruct and reconstruct the original String is anybody's guess.
Related
Am trying to reverse a string using a method in java, I can fetch all the elements of the string and print them out in order via a loop, my problem is reversing the string such that the first comes last and the last comes first, I tried to find a reverse function to no avail... Here is what I have so far...
private static void palindrome() {
char[] name = new char[]{};
String name1;
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
int len = name1.length();
for (int i = 0; i <= len; ++i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
}
That loop succeeds in printing out the single characters from the string.
You can use StringBuilder like this:
import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString {
public static void main(String[] args) {
String input = "Geeks for Geeks";
StringBuilder input1 = new StringBuilder();
// append a string into StringBuilder input1
input1.append(input);
// reverse StringBuilder input1
input1 = input1.reverse();
// print reversed String
System.out.println(input1);
}
}
You can also modify your code to do this:
1 -
for (int i = 0; i <= len; ++i) {
char b = name1[len - i];
System.out.println(b + " ");
}
2 -
for (int i = len; i >= 0; --i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
Using Java 9 codePoints stream you can reverse a string as follows. This example shows the reversal of a string containing surrogate pairs. It works with regular characters as well.
String str = "𝕙𝕖𝕝𝕝𝕠 𝕨𝕠𝕣𝕝𝕕";
String reversed = str.codePoints()
// Stream<String>
.mapToObj(Character::toString)
// concatenate in reverse order
.reduce((a, b) -> b + a)
.get();
System.out.println(reversed); // 𝕕𝕝𝕣𝕠𝕨 𝕠𝕝𝕝𝕖𝕙
See also: Reverse string printing method
You simply need to loop through the array backwards:
for (int i = len - 1; i >= 0; i--) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
You start at the last element which has its index at the position length - 1 and iterate down to the first element (with index zero).
This concept is not specific to Java and also applies to other data structures that provide index based access (such as lists).
Use the built-in reverse() method of the StringBuilder class.
private static void palindrome() {
String name1;
StringBuilder input = new StringBuilder();
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
input.append(name1);
input.reverse();
System.out.println(input);
}
Added reverse() function for your understanding
import java.util.Scanner;
public class P3 {
public static void main(String[] args) {
palindrome();
}
private static void palindrome() {
char[] name = new char[]{};
String name1;
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
String nameReversed = reverse(name1);
int len = name1.length();
for (int i = 0; i < len; ++i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
}
private static String reverse(String name1) {
char[] arr = name1.toCharArray();
int left = 0, right = arr.length - 1;
while (left < right) {
//swap characters first and last positions
char temp = arr[left];
arr[left++] = arr[right];
arr[right--] = temp;
}
return new String(arr);
}
}
you can try the build-in function charAt()
private String reverseString2(String str) {
if (str == null) {
return null;
}
String result = "";
for (int i = str.length() - 1; i >= 0; i--) {
result = result + str.charAt(i);
}
return result;
}
public void test(){
System.out.println(reverseString2("abcd"));
}
see also rever a string in java
String reversed = new StringBuilder(originalString).reverse().toString();
I'm trying to encrypt a message by the following code above.
Compare 2 string length and refill the short one with cycle back.
Convert that 2 string into a binary string.
XOR that 2 binary string to get another binary string.
convert the last binary string to hexadecimal.
Issue is on the last step. The output should be 111c0d131e1c180e1b10425655 instead of 111cd131e1c18e1b10425655.
Why my output missing two letters 0?
Can anyone help me to fix, please?
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Main
{
public static String StringToBinary(String str)
{
StringBuilder result = new StringBuilder();
char[] ch = str.toCharArray();
for (char character : ch)
{
result.append(String.format("%8s", Integer.toBinaryString(character)).replaceAll(" ", "0"));
}
return result.toString();
}
public static String XOR(String message, String password)
{
String tmp="";
for (int i = 0; i < message.length(); i++)
{
if (message.charAt(i) == password.charAt(i))
tmp += "0";
else
tmp += "1";
}
return tmp;
}
public static String convertBinaryToHexadecimal(String binaryStr)
{
return new BigInteger(binaryStr, 2).toString(16);
}
public static void main(String[] args)
{
int idx=0;
String msg = "poiuytrewq123";
String pwd = "asdfghjkl";
for(char m:msg.toCharArray())
{
idx = (idx < pwd.length()) ? idx : 0;
char p = pwd.charAt(idx);
idx++;
String stringOfMessageCharArray = String.valueOf(m);
String stringOfPasswordCharArray = String.valueOf(p);
String messageBinaryString = StringToBinary(stringOfMessageCharArray);
String passwordBinaryString = StringToBinary(stringOfPasswordCharArray);
String XorString = XOR(messageBinaryString,passwordBinaryString);
String cipherText = convertBinaryToHexadecimal(XorString);
System.out.print(cipherText);
}
}
}
The problem is that the number you are trying to convert from binary to hex is too small to require 2 characters, so it outputs just one.
public static String convertBinaryToHexadecimal(String binaryStr)
{
String hex = new BigInteger(binaryStr, 2).toString(16);
return hex.length() < 2 ? "0" + hex : hex;
}
If you change the function to this, it will put a 0 at the front of the hex if the length is less than 2, and return the right hex.
String tlv="80037665658104727265668203726564";
I want to print the above string TLV's separated with space like below
8003766565 810472726566 8203726564
eg. 80 -- Tag
03 -- Lengh
766565 -- value (every 2 digits like one byte total 3 bytes length)
Please help me above issue.
public static String tlv(String str1)
{
String slim="";
String str=str1+"00";
int tlvlen=0;
while(str.substring(tlvlen+0,tlvlen+2).matches("AA|A4|A9|1E|C0|C1|C2|C3|C4|C5|C6|C7|C8|C9|CA|CB|CC|A8|A0|4F|50|51|52|53|54|61|73|80|81|82|83|84|85|86|87|88|89|95"))
{
int len=Convertion.hex2decimal(str.substring(tlvlen+2,tlvlen+4))*2+4;
String tlv=str.substring(tlvlen,len+tlvlen);
slim+=tlv+" ";
tlvlen=tlv.length()+tlvlen;
}
return slim;
}
hear the convertion class has the hex2decimal method. This method will convert length hex to decimal.
public class Convertion {
public static int hex2decimal(String s) {
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16 * val + d;
}
return val;
}}
I don't know what's wrong with parsing the String to an int part in my code. Before the parsing, everything looks correct.
import java.io.IOException;
public class TheWindow {
public static void main(String[] args) throws IOException{
String s = "13.16";
double d = Double.parseDouble(s);
System.out.println(d);
char[] ch = s.toCharArray();
char[] ch2 = new char[s.length()];
for(int i = 0; i < ch.length; i++){
if(ch[i] == '.'){
break;
}else{
ch2[i] = ch[i];
}
}
String s2 = new String(ch2);
System.out.println(s2);
try{
s2.trim();
int newI = Integer.parseInt(s2);
System.out.println(newI);
}catch(Exception e){
System.out.println("Failed");
}
}
}
You are not storing the returned String from trim() anywhere. You could either do:
s2 = s2.trim();
int newI = Integer.parseInt(s2);
or
int newI = Integer.parseInt(s2.trim());
The problem with your code is that you are breaking out of the for loop when the '.' character is reached.
Since you created ch2 with a length of 5 then this means the last three spaces are null. When you put that in a string with String s2 = new String(ch2) then then three special characters are added at the end of the string, one for each empty space in the ch2 character array.
To fix this then set the length of the ch2 array to be two, or if you want to dynamically determine the length, do the index of the '' in theString swiths.indexOf('.')and then set the length of the array to one minus the index of ''.
This should fix your problem as stated in your question.
s2 = s2.trim();
change this part of code in the try block.
You are trimming the string but not assigning it to the variable that refers it due to which the spaces are still left out and parsing such string is throwing an exception.
Java objects are immutable, meaning they can't be changed, and Strings are Objects in Java.
Your line s2.trim() will return the trimmed version, but s2 will not be directly modified. However, you aren't storing it anywhere, so when you parse it on the next line, it will be with the untrimmed s2.
What you want is s2 = s2.trim(), which will store the trimmed version back in.
From what I understand, you want to truncate the decimal. If so, then you can just find the decimal place and substring the string, then parse it.
Note: You might want to add back in some try-catches for strings that still cannot be parsed.
private static int tryParseInt(String str) {
int decimalIndex = str.indexOf(".");
if (decimalIndex != -1) {
return Integer.parseInt(str.substring(0, decimalIndex));
} else {
return Integer.parseInt(str);
}
}
public static void main(String[] args) {
System.out.println(tryParseInt("13.16")); // 13
}
You have uninitialized characters in your ch2 array. You can set them to space before trimming or use a different string constructor. For example:
public static void main(String[] args) {
String s = "13.16";
double d = Double.parseDouble(s);
System.out.println(d);
char[] ch = s.toCharArray();
char[] ch2 = new char[s.length()];
int i = 0;
for(i = 0; i < ch.length; i++){
if(ch[i] == '.'){
break;
}else{
ch2[i] = ch[i];
}
}
String s2 = new String(ch2, 0, i);
System.out.println(s2);
try{
s2.trim();
int newI = Integer.parseInt(s2);
System.out.println(newI);
}catch(Exception e){
System.out.println("Failed");
}
}
}
I want to store the value of 2 strings str1, str2 respectively into 3rd string strContainer (without using library method).
My Algorithm is:
1. convert str1 and str2 into character array charArray1 and charArray2 respectively.
2. Count the sum of the length of both character array in counter variable (sum of the length charArray and charArray2)
3. Sum of the both char Arrays (as counter) is equivalent to a new char Array charContainer.
4. Iterate a loop as below
charContainer[ith index] += charArray1[ith index];
and
charContainer[ith index] += charArray2[ith index];
5. Convert charContainer into string and display as strContainer.
My code so far:
public class StringConcat{
int counter; // counting the length of char arrays
String str1 = "FirstString";
String str2 = "SecondString";
//for counting the length of both char arrays
public int countingLength(String str){
char[] strToCharArray = str.toCharArray();
for(char temp : strToCharArray){
counter++;
}
}
//converting string into char array
char[] charArray1 = str1.tocharArray();
char[] charArray2 = str1.tocharArray();
//stores both char array
char[] charContainer=new char[counter];//how to take counter as an index value here
//for storing charArray1 into charContainer
for(int i=0; i<charContainer.length; i++) {
if(charArray1 != null){
charContainer[i] += charArray1[i];
} else
return charArray2;
}
//for storing charArray2 into charContainer
for(int i=0; i<charContainer.length; i++) {
if(charArray2 != null){
charContainer[i] += charArray1[i];
} else
return charArray1;
}
//converting charContainer char array into string strContainer.
String strContainer = new String(charContainer);
//alternative : String strContainer = String.valueOf(charContainer);
public static void main(String args[]){
/*Here i can call (As i'm not sure)
StringConcat obj1 = new StringConcat();
obj1.countingLength(str1);
StringConcat obj2 = new StringConcat();
obj2.countingLength(str2);
*/
System.out.println("String Container : " +strContainer);
}
}//end of the class
Issues:
How to call countingLength() method for both strings str1 and str2 ?
How to assign as an index value of charContainer as counter (sum of the both char arrays) ?
How to call StringLengthCounter() method? I can't see any method with that name.. I'm sorry but that is not the problem here, the problem is that this is not even valid code.
I don't mean to be harsh but there are sintax error all around and the program logic is wrong in many ways.
Please take a look at the following code and try to figure out how it works, I think it does what you want.
If something isn't clear just ask.
public class StringConcat{
public static String strcat(String str1, String str2){
//converting string into char array
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
int counter=charArray1.length+charArray2.length;
//stores both char array
char[] charContainer=new char[counter];
//for storing charArray1 into charContainer
int i=0;
for(; i<charArray1.length; i++) {
charContainer[i]=charArray1[i];
}
//for storing charArray2 into charContainer
for(int j=0; i<counter; j++,i++) {
charContainer[i]=charArray2[j];
}
//converting charContainer char array into string
return new String(charContainer);
}
public static void main(String args[]){
String str1 = "FirstString";
String str2 = "SecondString";
String strContainer = strcat(str1,str2);
System.out.println("String Container : " +strContainer);
}
}//end of the class
import java.io.*;
class Concatenation
{
public static void main(String []args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i=0;
String s1,s2;
System.out.print("Enter the first string:");
s1=br.readLine();
System.out.print("Enter the Second string:");
s2=br.readLine();
char s3[]=new char[s1.length()+s2.length()];
for(;i<s1.length();i++)
s3[i]=s1.charAt(i);
for(int j=0;j<s2.length();j++)
s3[i++]=s2.charAt(j);
System.out.println("Result:"+new String(s3));
}
}
public class Conc {
String s1="java",s2="programming",s3="";
int l=s1.length(),m=s2.length(),i,j;
public String conca(String s1,String s2){
for(i=0;i<=l-1;i++){
s3+=s1.charAt(i);
}
for(j=0;j<=m-1;j++){
s3+=s2.charAt(j);
}
System.out.println(s3);
return s3;
}
public static void main(String[] args) {
Conc obj1=new Conc();
obj1.conca("java","programming");
}
}
public class StringConcatination {
public static String concate(String s1,String s2){
String s3="";
for(int i=0;i<s1.length();i++){
s3+=s1.charAt(i);
}
for(int j=0;j<s2.length();j++){
s3+=s2.charAt(j);
}
return s3;
}
public static void main(String[] args) {
System.out.println(concate("java","programming"));
}
}
public static void concat(String a, String b) {
/**
* String result = a + b;
*/
/**
* Logic goes here.
*
* Need to iterate through chars
*
* Need to get total length
*/
int totalLength = a.length();
totalLength += b.length();
char[] result = new char[totalLength];
char[] arrayFromA = a.toCharArray();
char[] arrayFromB = b.toCharArray();
int count = 0;
System.out.println("Total Length of String: "+ totalLength);
for (int i = 0; i < arrayFromA.length; i++) {
result[i] = arrayFromA[i];
count++;
}
for (int j = 0; j < arrayFromB.length; j++) {
result[count] = arrayFromB[j];
count++;
}
System.out.println(new String(result));
}