This question already has answers here:
Converting some hexadecimal string to a decimal integer
(13 answers)
Closed 4 years ago.
I am currently writing a program that reads the ID of NFC Tags and reverses them. The thing I am trying to accomplish now is to convert that reversed ID from Hex to Dec
Let's say that the ID of the number would be "3bde4eac", so the reversed result would be "ac4edb3b"
And I don't really know how to correctly convert that HexString to Decimal.
Here is my current code:
else{
String tagInfo = tag.toString() + "\n";
tagInfo = "";
byte[] tagId = tag.getId();
for(int i=n; i<tagId.length; i++){
tagInfo += Integer.toHexString(tagId[i] & 0xFF);
}
String s = tagInfo;
StringBuilder result = new StringBuilder();
for(int n = 0; n <=s.length()-2; n=n+2) {
result.append(new StringBuilder(s.substring(n, n + 2)).reverse());
}
s = result.reverse().toString();
Long f = Long.parseLong(s, 16);
textViewInfo.setText(s);
}
EDIT: Using the "duplicate link", I was able to solve the problem.
I changed the last part of my code to
s = result.reverse().toString();
Long g = hex2decimal(s);
textViewInfo.setText(g.toString());
With the function
public static Long hex2decimal(String s) {
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
long val = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
long d = digits.indexOf(c);
val = 16*val + d;
}
return val;
}
You should try parsing the reversed string as hexadecimal and then convert the obtained int value to decimal. Check out Integer.parseInt(strValue, 16) to parse String in base16/hexadecimal and Integer.toString(intValue) for this.
Related
I need to combine an array of strings as below ( so as each character in the result string is a bitwise & of the characters in the input string)
String a = "10110001"
String b = "01101101"
String c = "10101011"
String result = "00100001"
Solution I came up with:
long resultLong = 0;
for( String a : inputs )
{
resultLong = resultLong & Long.parseLong( a ,2);
}
String result = Long.toBinaryString( resultLong );
The number of characters in the input string could be very long, and the above solution wouldn't work (NumberFormatException) . I couldn't get my head around how to implement this, what would be the cleanest way ?
If Long is not enough for your use case then you can use BigInteger
BigInteger(String val, int radix);
Which takes a String and radix as the arguments.
BigInteger result = new BigInteger(inputs[0], 2);
for (int i = 1; i < inputs.length; i++) {
result = result.and(new BigInteger(inputs[i], 2));
}
String resultStr = result.toString(2);
Here's your algorithm. This will work for any number of Strings provided that all the Strings are of same length:
public static void main(String[] args) {
String a = "10110001";
String b = "01101101";
String c = "10101011";
String arr[] = new String[]{a, b, c};
String finalString = "";
for (int i = 0; i < arr[0].length(); i++) {
int temp = Integer.parseInt("" + arr[0].charAt(i));
for (int j = 1; j < arr.length; j++) {
temp = temp & Integer.parseInt("" + arr[j].charAt(i));
}
finalString += temp;
}
System.out.println(finalString);
}
O/P
00100001
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.
Say I have a binary string ("0 and 1s") and I want to write this string to a binary file, how can this be done in java? I tried converting to ASCII values string, then create a ByteArrayInputStream from that but values over 127 do not display correctly. Can anyone help me with this?
My binaryToAscii method:
public static String BinaryToAscii(String bin){
int num_of_bytes = bin.length()/8;
StringBuilder sb = new StringBuilder();
int index = 0;
String byte_code;
Character char_code;
for (int i =0; i<num_of_bytes;i++){
index = i*8;
byte_code = bin.substring(index,index+8);
int charCode = Integer.parseInt(byte_code, 2);
char_code = new Character((char)charCode);
sb.append(char_code);
}
return sb.toString();
}
Then I convert the returned string to a ByteArrayInputStream using
InputStream is = new ByteArrayInputStream(ascii.toString().getBytes());
you first would transform the 0 / 1 string to a byte[].
then write out using
DataOutputStream.writeByte().
read in with
DataInputStream.readUnsignedByte() // to get 0 - 255
To convert string to binary use this:
You will first need to break the string into its individual letters then run them through this one at a time.
char letter = c;
byte[] bytes = letter.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
System.out.println(binary);
I am struggling trying to convert a hex number string back to the original string. I convert the string using the following method:
private static String hex(String binStr) {
String newStr = new String();
try {
String hexStr = "0123456789ABCDEF";
byte [] p = binStr.getBytes();
for(int k=0; k < p.length; k++ ){
int j = ( p[k] >> 4 )&0xF;
newStr = newStr + hexStr.charAt( j );
j = p[k]&0xF;
newStr = newStr + hexStr.charAt( j ) + " ";
}
} catch (Exception e) {
System.out.println("Failed to convert into hex values: " + e);
}
return newStr;
}
I am really stuck, and any advice would be greatly appreciated.
Thank you in advance
Consider this:
String hexStr = "0123456789ABCDEF";
long i = Long.valueOf(hexStr, 16);
System.out.println(Long.toHexString(i));
The code in the question destroys information. Only the most significant two bits and the least significant four bits of each input byte contribute to the result. That means it cannot, in general, be reversed.
If the right shift had been by four bits, instead of 6:
int j = ( p[k] >> 4 )&0xF;
all the input would have been preserved, and the original string could have been recovered from the hex string. Maybe you really meant the four bit shift?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Binary to text in Java
I'm writing a program that can convert multiple things, but I need help with the converting of binary. I have my code for text-to-binary working, but I'm not sure about binary-to-text. Here is my code for the button which triggers the conversion:
String code = jTextArea5.getText();
if (code == null) {
System.out.println(jTextArea1.getText( ));
String writing = jTextArea1.getText();
byte[] bytes = writing.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes) {
int val = b;
for (int i = 0; i < 8; i++){
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
jTextArea5.setText("" + binary);
}
else
{
System.out.println(jTextArea1.getText( ));
String binary = jTextArea1.getText();
int ascii = Integer.parseInt(binary, 2);
char character = (char)ascii;
jTextArea5.setText("" + character);
}
If anyone knows how I can fix this code to work, that'd be great. Thanks!
NOTE - This bit below works on it's own, just not in conjunction with any efforts to allow converting binary in jTextArea5 to text in jTextArea1.
System.out.println(jTextArea1.getText( ));
String writing = jTextArea1.getText();
byte[] bytes = writing.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes) {
int val = b;
for (int i = 0; i < 8; i++){
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
jTextArea5.setText("" + binary);
Convert the binary into an integer:
String binary = "010101";
int ascii = Integer.parseInt(binary, 2);
Then turn the integer into ascii:
char character = (char)ascii;
Swap the 5 and the 1 around so it grabs the binary out of the correct textbox.
And use StringTokenizer to process each block of 8
Dont forget to import StringTokenizer
else
{
System.out.println(jTextArea5.getText( ));
String binary = jTextArea5.getText();
StringTokenizer st = new StringTokenizer(binary," ");
while(st.hasMoreTokens()){
int ascii = Integer.parseInt(st.nextToken(), 2);
char character = (char)ascii;
jTextArea1.setText(jTextArea1.getText() + "" + character);
}
}
this bit checks whats in jTextArea5.getText()
if (code == null) {
change it to
if (code.equals("")) {
and make sure you clear out whats in the text boxes before you start either conversion