I am trying to convert string ABCDEF1234567890 to decimal value:
long result = 0;
String hex = "0123456789ABCDEF";
decimal = decimal.toUpperCase();
for(int i = 0; i < decimal.length(); i++) {
char c = decimal.charAt(i);
result += hex.indexOf(c) * Math.pow(16, decimal.length() - 1 - i);
}
return Long.toString(result);
I know the class BigInteger but i don't know how to use it in my code. please help me
The BigInteger class has a constructor which accepts a string and radix:
final BigInteger bigInt = new BigInteger(hex, 16);
Note that your specific hex value 0123456789ABCDEF fits into a variable of type long (Long.MAX_VALUE == 0x7fffffffffffffffL) and Long#parseLong accepts a string and radix as well:
final long value = Long.parseLong(hex);
Related
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println(input);
int a = Integer.parseInt(input.substring(2), 16);
System.out.println(Integer.toBinaryString(a));
Above mentioned code that takes in hex value and convert it into binary. However, this would not work on input "0xBE400000" but it works fine for "0x41C20000"
BE400000 is larger than Integer.MAX_VALUE (whose hex representation is 7FFFFFFF).
Therefore you'll need to parse it with
long a = Long.parseLong(input.substring(2), 16);
Since 0xBE400000 is in the range of an unsigned int you can use: parseUnsignedInt(String s, int radix)
int a = Integer.parseUnsignedInt(input.substring(2), 16);
With parseUnsignedInt(input, 16) you can parse values from 0x00000000 to 0xFFFFFFFF, where:
0x00000000 = 0
0x7FFFFFFF = 2147483647 (Integer.MAX_VALUE)
0x80000000 = -2147483648 (Integer.MIN_VALUE)
0xFFFFFFFF = -1
0xBE400000 = -1103101952
You can use Long
long l = Long.parseLong(input.substring(2), 16);
but if your value is greater than 2^63 - 1 you may use use a BigInteger's constructor:
BigInteger(String val, int radix)
Translates the String representation of a BigInteger in the specified radix into a BigInteger.
BigInteger b = new BigInteger(input.substring(2), 16);
I'm looking for a better way to convert an int to 64 bit binary represented as String. Right now I'm converting int to 32bit binary and then adding 32 zeroes in front of it. I'm implementing SHA-1 and I need that int to be 64bit binary.
private static String convertIntTo64BitBinary(int input) {
StringBuilder convertedInt = new StringBuilder();
for(int i = 31; i >= 0; i--) { // because int is 4 bytes thus 32 bits
int mask = 1 << i;
convertedInt.append((input & mask) != 0 ? "1" : "0");
}
for(int i = 0; i < 32; i++){
convertedInt.insert(0, "0");
}
return convertedInt.toString();
}
EDIT 1:
Unfortunately this doesn't work:
int messageLength = message.length();
String messageLengthInBinary = Long.toBinaryString((long) messageLength);
messageLengthInBinary is "110"
EDIT 2:
To clarify:
I need the string to be 64 chars long so need all the leading zeros.
You could use the long datatype which is a 64 bit signed integer. Then calling Long.toBinaryString(i) would give you the binary representation of i
If you already have an int then you could cast it to a long and use the above.
This doesn't include the leading 0s so the resulting string needs padding to the 64 characters.
Something like this would work.
String value = Long.toBinaryString(i)
String zeros = "0000000000000000000000000000000000000000000000000000000000000000" //String of 64 zeros
zeros.substring(value.length()) + value;
See How can I pad a String in Java? for more options.
Given a binary number as input convert it into base 10 (decimal system). Note that to convert a number 100111 from binary to decimal, the value is 1*2^5 + 0*2^4 + 0*2^3 + 1*2^2 + 1*2^1+ 1*2^0. Also note that 5 here is the length of the binary number.
MyApproach
To convert to decimal,I first converted the code from String to decimal.Then I solved the number till it is greater than 0 and solved the expression.
For example for number 10=0*2^0+1*2^1 and solved the expression in the code.
I am getting a wrong Ans on the last test case.
Can anyone guide me what is wrong in my code.?
Below is my code:
public int convert(String binary)
{
int p=0;
int decimal=0;
int number=Integer.parseInt(binary);
while(number>0)
{
int temp = number%10;
decimal += temp*Math.pow(2, p);
number = number/10;
p++;
//write your code here
}
return decimal;
}
}
Parameters ActualOutput ExpectedOutput
'10011010010' null 1234
Max value of integer is (2^31-1) and the value that you are parsing to int from string in greater than that. Hence try to use Long in place of int ..
below code is working fine.. please check it below..
public static int convert(String binary)
{
int p=0;
int decimal=0;
long number=Long.parseLong(binary);
while(number>0)
{
long temp = number%10;
decimal += temp*Math.pow(2, p);
number = number/10;
p++;
//write your code here
}
return decimal;
}
Simpler, without pow :
int s=binary.length();
for (int pos=0;pos<s;pos++)
{
char c=binary.charAt(pos);
if (c=='1') decimal+=1;
if (pos<s-1) decimal*=2;
}
Why convert it to decimal first? This is quite easy:
public static void main( String[] args ) {
String str = "10011010010";
int len = str.length();
long mult = 1;
long val = 0;
for (int i = len - 1; i >= 0; i--) {
if ( str.charAt( i ) == '1' ) {
val += mult;
}
mult *= 2;
}
System.out.println( val );
}
Your input is above the limit of int in Java, which is 2,147,483,647.
Even if if you change it to long, you won't be able to convert values above 1000000000000000000 (which is equal to 262144 in decimal). Best solution is to calculate by taking character by character without converting the whole string.
So, try the following code,
public static long convert(String binary) {
long pow = 1, decimal = 0;
for (int i = (binary.length() - 1); i >= 0; i--) {
if (binary.charAt(i) == '1') {
decimal += pow;
}
pow *= 2;
}
return decimal;
}
I have the following code in Java:
int hex = 0x63;
The decimal value of 6316 is equal to 9910. I would like to convert this hex value to a decimal that is equal to 6310.
the hex value is 0x63, I want to have a decimal value as 63 based on the hex value
This is called a Binary-coded decimal (BCD) representation. There are many ways to convert a number from BCD to decimal. Perhaps the simplest one is to print it as hex, and then parse it back as a decimal:
int hex = 0x63;
int dec = Integer.valueOf(Integer.toHexString(hex), 10);
Demo on ideone.
you can use this:
int hex = 0x63;
int decimalValue = Integer.parseInt(hex+"", 10);
System.out.println("Decimal value is :" + decimalValue);
try this:
int hex = 0x63F2FC;//just an example (containg letters)
String hexStr = Integer.toHexString(hex);
String decimal = "";
char[] tmp = hexStr.toCharArray();
for (int i = 0; i < tmp.length ; i++)
decimal += (Character.isDigit(tmp[i])?tmp[i]+"":"");
I am new at Java. I am learning.
I am trying to do the following:
convert a hexadecimal string into a binary, then process the binary into a series of booleans.
public static void getStatus() {
/*
* CHECKTOKEN is a 4 bit hexadecimal
* String Value in FF format.
* It needs to go into binary format
*/
//LINETOKEN.nextToken = 55 so CHECKTOKEN = 55
CHECKTOKEN = LINETOKEN.nextToken();
//convert to Integer (lose any leading 0s)
int binaryToken = Integer.parseInt(CHECKTOKEN,16);
//convert to binary string so 55 becomes 85 becomes 1010101
//should be 01010101
String binaryValue = Integer.toBinaryString(binaryToken);
//Calculate the number of required leading 0's
int leading0s = 8 - binaryValue.length();
//add leading 0s as needed
while (leading0s != 0) {
binaryValue = "0" + binaryValue;
leading0s = leading0s - 1;
}
//so now I have a properly formatted hex to binary
//binaryValue = 01010101
System.out.println("Indicator" + binaryValue);
/*
* how to get the value of the least
* signigicant digit into a boolean
* variable... and the next?
*/
}
I think there must be a better way to perform the action. This is not elegant. Also, I'm stuck with a binary string value which needs to be processed somehow.
public static void main(String[] args) {
String hexString = "55";
int value = Integer.parseInt(hexString, 16);
int numOfBits = 8;
boolean[] booleans = new boolean[numOfBits];
for (int i = 0; i < numOfBits; i++) {
booleans[i] = (value & 1 << i) != 0;
}
System.out.println(Arrays.toString(booleans));
}