Java Convert integer to hex integer - java

I'm trying to convert a number from an integer into an another integer which, if printed in hex, would look the same as the original integer.
For example:
Convert 20 to 32 (which is 0x20)
Convert 54 to 84 (which is 0x54)

The easiest way is to use Integer.toHexString(int)

public static int convert(int n) {
return Integer.valueOf(String.valueOf(n), 16);
}
public static void main(String[] args) {
System.out.println(convert(20)); // 32
System.out.println(convert(54)); // 84
}
That is, treat the original number as if it was in hexadecimal, and then convert to decimal.

Another way to convert int to hex.
String hex = String.format("%X", int);
You can change capital X to x for lowercase.
Example:
String.format("%X", 31) results 1F.
String.format("%X", 32) results 20.

int orig = 20;
int res = Integer.parseInt(""+orig, 16);

You could try something like this (the way you would do it on paper):
public static int solve(int x){
int y=0;
int i=0;
while (x>0){
y+=(x%10)*Math.pow(16,i);
x/=10;
i++;
}
return y;
}
public static void main(String args[]){
System.out.println(solve(20));
System.out.println(solve(54));
}
For the examples you have given this would calculate: 0*16^0+2*16^1=32 and 4*16^0+5*16^1=84

String input = "20";
int output = Integer.parseInt(input, 16); // 32

The following is optimized iff you only want to print the hexa representation of a positive integer.
It should be blazing fast as it uses only bit manipulation, the utf-8 values of ASCII chars and recursion to avoid reversing a StringBuilder at the end.
public static void hexa(int num) {
int m = 0;
if( (m = num >>> 4) != 0 ) {
hexa( m );
}
System.out.print((char)((m=num & 0x0F)+(m<10 ? 48 : 55)));
}

Simply do this:
public static int specialNum(num){
return Integer.parseInt( Integer.toString(num) ,16)
}
It should convert any special decimal integer to its hexadecimal counterpart.

Related

How do I convert a string of numbers to an integer array?

I have a string like, "12345" and want to convert it to the integer array, {1,2,3,4,5}.
I want one method to convert a character to an integer, '1' -> 1. And another method to create the array.
This is what I have so far:
public static int charToInt(char character) {
int newInt;
newInt = (int) character;
return newInt;
}
public static int[] convertStringToIntArray(String keyString) {
int keyLength = keyString.length();
int element;
int[] intArray = new int[keyLength];
for (element = 0; element < keyLength; element++) {
intArray[element] = charToInt(keyString.charAt(element));
}
// return
return intArray;
}
I think the problem is in the charToInt method. I think it is converting the char to its ascii value. But I am not sure if the other method is right either.
Any help would be greatly appreciated.
Since Java 1.5 Character has an interesting method getNumericValue which allows to convert char digits to int values.
So with the help of Stream API, the entire method convertStringToIntArray may be rewritten as:
public static int[] convertStringToIntArray(String keyString) {
Objects.requireNonNull(keyString);
return keyString.chars().map(Character::getNumericValue).toArray();
}
You are right. The problem here is in charToInt.
(int) character is just the ascii codepoint (or rather UTF-16 codepoint).
Because the digits '0' to '9' have increasing codepoints you can convert any digit into a number by subtracting '0'.
public static int charToInt(char digit)
{
return digit - '0';
}
This might help -
int keyLength = keyString.length();
int num = Integer.parseInt(keyString);
int[] intArray = new int[ keyLength ];
for(int i=keyLength-1; i>=0; i--){
intArray[i] = num % 10;
num = num / 10;
}
Since Java 9 you can use String#codePoints method.
Try it online!
public static int[] convertStringToIntArray(String keyString) {
return keyString.codePoints().map(Character::getNumericValue).toArray();
}
public static void main(String[] args) {
String str = "12345";
int[] arr = convertStringToIntArray(str);
// output
System.out.println(Arrays.toString(arr));
// [1, 2, 3, 4, 5]
}

Convert integer to byte in java

I am looking for a way to convert an integer value (like 22, 32, 42) to the corresponding fake hex value (like 0x22, 0x32, 0x42).
Can anyone have a solution for this type of problem?
If you just want the 0x appended: "0x"+value. If you want to convert the int to the appropriate number for that hex value
String temp = Integer.toString(value);
int asHex = Integer.valueOf(temp, 16);
I don't know why you want this, it seems strange you won't ever output 0xA through 0xF (because it can't be in the input) but here it is anyway, I hope it at least helps you spot the probable flaw in your approach:
public static int fakeHex(int i) {
int result = 0;
int base = 1;
while (i > 0) {
int decimalDigit = i % 10;
result += base * decimalDigit;
i /= 10;
base *= 16;
}
return result;
}
Test cases:
#Test
public void fake_hex_test() {
assertEquals(0x0, fakeHex(0));
assertEquals(0x9, fakeHex(9));
assertEquals(0x22, fakeHex(22));
assertEquals(0x32, fakeHex(32));
assertEquals(0x42, fakeHex(42));
assertEquals(0x123, fakeHex(123));
}

Convert a given decimal string into a binary string(even number of binary digits) in Java [duplicate]

for example, for 1, 2, 128, 256 the output can be (16 digits):
0000000000000001
0000000000000010
0000000010000000
0000000100000000
I tried
String.format("%16s", Integer.toBinaryString(1));
it puts spaces for left-padding:
` 1'
How to put 0s for padding. I couldn't find it in Formatter. Is there another way to do it?
P.S. this post describes how to format integers with left 0-padding, but it is not for the binary representation.
I think this is a suboptimal solution, but you could do
String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0')
There is no binary conversion built into the java.util.Formatter, I would advise you to either use String.replace to replace space character with zeros, as in:
String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0")
Or implement your own logic to convert integers to binary representation with added left padding somewhere along the lines given in this so.
Or if you really need to pass numbers to format, you can convert your binary representation to BigInteger and then format that with leading zeros, but this is very costly at runtime, as in:
String.format("%016d", new BigInteger(Integer.toBinaryString(1)))
Here a new answer for an old post.
To pad a binary value with leading zeros to a specific length, try this:
Integer.toBinaryString( (1 << len) | val ).substring( 1 )
If len = 4 and val = 1,
Integer.toBinaryString( (1 << len) | val )
returns the string "10001", then
"10001".substring( 1 )
discards the very first character. So we obtain what we want:
"0001"
If val is likely to be negative, rather try:
Integer.toBinaryString( (1 << len) | (val & ((1 << len) - 1)) ).substring( 1 )
You can use Apache Commons StringUtils. It offers methods for padding strings:
StringUtils.leftPad(Integer.toBinaryString(1), 16, '0');
I was trying all sorts of method calls that I haven't really used before to make this work, they worked with moderate success, until I thought of something that is so simple it just might work, and it did!
I'm sure it's been thought of before, not sure if it's any good for long string of binary codes but it works fine for 16Bit strings. Hope it helps!! (Note second piece of code is improved)
String binString = Integer.toBinaryString(256);
while (binString.length() < 16) { //pad with 16 0's
binString = "0" + binString;
}
Thanks to Will on helping improve this answer to make it work with out a loop.
This maybe a little clumsy but it works, please improve and comment back if you can....
binString = Integer.toBinaryString(256);
int length = 16 - binString.length();
char[] padArray = new char[length];
Arrays.fill(padArray, '0');
String padString = new String(padArray);
binString = padString + binString;
A simpler version of user3608934's idea "This is an old trick, create a string with 16 0's then append the trimmed binary string you got ":
private String toBinaryString32(int i) {
String binaryWithOutLeading0 = Integer.toBinaryString(i);
return "00000000000000000000000000000000"
.substring(binaryWithOutLeading0.length())
+ binaryWithOutLeading0;
}
I do not know "right" solution but I can suggest you a fast patch.
String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0");
I have just tried it and saw that it works fine.
Starting with Java 11, you can use the repeat(...) method:
"0".repeat(Integer.numberOfLeadingZeros(i) - 16) + Integer.toBinaryString(i)
Or, if you need 32-bit representation of any integer:
"0".repeat(Integer.numberOfLeadingZeros(i != 0 ? i : 1)) + Integer.toBinaryString(i)
try...
String.format("%016d\n", Integer.parseInt(Integer.toBinaryString(256)));
I dont think this is the "correct" way to doing this... but it works :)
I would write my own util class with the method like below
public class NumberFormatUtils {
public static String longToBinString(long val) {
char[] buffer = new char[64];
Arrays.fill(buffer, '0');
for (int i = 0; i < 64; ++i) {
long mask = 1L << i;
if ((val & mask) == mask) {
buffer[63 - i] = '1';
}
}
return new String(buffer);
}
public static void main(String... args) {
long value = 0b0000000000000000000000000000000000000000000000000000000000000101L;
System.out.println(value);
System.out.println(Long.toBinaryString(value));
System.out.println(NumberFormatUtils.longToBinString(value));
}
}
Output:
5
101
0000000000000000000000000000000000000000000000000000000000000101
The same approach could be applied to any integral types. Pay attention to the type of mask
long mask = 1L << i;
A naive solution that work would be
String temp = Integer.toBinaryString(5);
while (temp.length() < Integer.SIZE) temp = "0"+temp; //pad leading zeros
temp = temp.substring(Integer.SIZE - Short.SIZE); //remove excess
One other method would be
String temp = Integer.toBinaryString((m | 0x80000000));
temp = temp.substring(Integer.SIZE - Short.SIZE);
This will produce a 16 bit string of the integer 5
// Below will handle proper sizes
public static String binaryString(int i) {
return String.format("%" + Integer.SIZE + "s", Integer.toBinaryString(i)).replace(' ', '0');
}
public static String binaryString(long i) {
return String.format("%" + Long.SIZE + "s", Long.toBinaryString(i)).replace(' ', '0');
}
This is an old trick, create a string with 16 0's then append the trimmed binary string you got from String.format("%s", Integer.toBinaryString(1)) and use the right-most 16 characters, lopping off any leading 0's. Better yet, make a function that lets you specify how long of a binary string you want. Of course there are probably a bazillion other ways to accomplish this including libraries, but I'm adding this post to help out a friend :)
public class BinaryPrinter {
public static void main(String[] args) {
System.out.format("%d in binary is %s\n", 1, binaryString(1, 4));
System.out.format("%d in binary is %s\n", 128, binaryString(128, 8));
System.out.format("%d in binary is %s\n", 256, binaryString(256, 16));
}
public static String binaryString( final int number, final int binaryDigits ) {
final String pattern = String.format( "%%0%dd", binaryDigits );
final String padding = String.format( pattern, 0 );
final String response = String.format( "%s%s", padding, Integer.toBinaryString(number) );
System.out.format( "\npattern = '%s'\npadding = '%s'\nresponse = '%s'\n\n", pattern, padding, response );
return response.substring( response.length() - binaryDigits );
}
}
This method converts an int to a String, length=bits. Either padded with 0s or with the most significant bits truncated.
static String toBitString( int x, int bits ){
String bitString = Integer.toBinaryString(x);
int size = bitString.length();
StringBuilder sb = new StringBuilder( bits );
if( bits > size ){
for( int i=0; i<bits-size; i++ )
sb.append('0');
sb.append( bitString );
}else
sb = sb.append( bitString.substring(size-bits, size) );
return sb.toString();
}
You can use lib https://github.com/kssource/BitSequence. It accept a number and return bynary string, padded and/or grouped.
String s = new BitSequence(2, 16).toBynaryString(ALIGN.RIGHT, GROUP.CONTINOUSLY));
return
0000000000000010
another examples:
[10, -20, 30]->00001010 11101100 00011110
i=-10->00000000000000000000000000001010
bi=10->1010
sh=10->00 0000 0000 1010
l=10->00000001 010
by=-10->1010
i=-10->bc->11111111 11111111 11111111 11110110
for(int i=0;i<n;i++)
{
for(int j=str[i].length();j<4;j++)
str[i]="0".concat(str[i]);
}
str[i].length() is length of number say 2 in binary is 01 which is length 2
change 4 to desired max length of number. This can be optimized to O(n).
by using continue.
import java.util.Scanner;
public class Q3{
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
System.out.println("Enter a number:");
int num=scn.nextInt();
int numB=Integer.parseInt(Integer.toBinaryString(num));
String strB=String.format("%08d",numB);//makes a 8 character code
if(num>=1 && num<=255){
System.out.println(strB);
}else{
System.out.println("Number should be in range between 1 and 255");
}
}
}

How to count total number of chars in float number

Could you help me to write a method with the following signature:
public int method(double value)
that returns total number of chars in value(including the decimal point), for example:
method(5.0) - 3
method(1.2345) - 6
method(2.34) - 4
The problem is that method(5) must return 1, not 3, looking at 5 as it is 5.0
Change the value argument to string and find its length as follow:
String valueString = value+"";
int count = valueString.length()
Do this inside your method()
Update:
public static int method(double value){
String temp;
if(value == (long) value)
temp = String.format("%d",(long)value);
else
temp = String.format("%s",value);
return temp.length();
}
--
Input: 5.01 gives Output: 4
Input: 5.0 gives Output: 1
First , convert the double to string, and then calculate its size.
String str = String.valueOf(yourDoubleNumber);
int charCount = str.length();
it will give you the size of string i.e character count
Doubles and floats don't have chars. They have bits. If you're asking about decimal digits, you would first have to convert to a decimal radix.
int method(double value) {
if (value == (int) value)
return Integer.toString((int)value).length();
else return Double.toString(value).length();
}
Overload your method with an int argument method, and then apply your logic as before.
public int method(double d){
//your logic
}
public int method(int i){
//your logic
}`enter code here

How to concatenate int values in java?

I have the following values:
int a=1;
int b=0;
int c=2;
int d=2;
int e=1;
How do i concatenate these values so that i end up with a String that is 10221;
please note that multiplying a by 10000, b by 1000.....and e by 1 will not working since b=0 and therefore i will lose it when i add the values up.
The easiest (but somewhat dirty) way:
String result = "" + a + b + c + d + e
Edit: I don't recommend this and agree with Jon's comment. Adding those extra empty strings is probably the best compromise between shortness and clarity.
Michael Borgwardt's solution is the best for 5 digits, but if you have variable number of digits, you can use something like this:
public static String concatenateDigits(int... digits) {
StringBuilder sb = new StringBuilder(digits.length);
for (int digit : digits) {
sb.append(digit);
}
return sb.toString();
}
This worked for me.
int i = 14;
int j = 26;
int k = Integer.valueOf(String.valueOf(i) + String.valueOf(j));
System.out.println(k);
It turned out as 1426
just to not forget the format method
String s = String.format("%s%s%s%s%s", a, b, c, d, e);
(%1.1s%1.1s%1.1s%1.1s%1.1s if you only want the first digit of each number...)
Actually,
int result = a * 10000 + b * 1000 + c * 100 + d * 10 + e;
String s = Integer.toString(result);
will work.
Note: this will only work when a is greater than 0 and all of b, c, d and e are in [0, 9]. For example, if b is 15, Michael's method will get you the result you probably want.
How about not using strings at all...
This should work for any number of digits...
int[] nums = {1, 0, 2, 2, 1};
int retval = 0;
for (int digit : nums)
{
retval *= 10;
retval += digit;
}
System.out.println("Return value is: " + retval);
StringBuffer sb = new StringBuffer();
sb.append(a).append(b).append(c)...
Keeping the values as an int is preferred thou, as the other answers show you.
If you multiply b by 1000, you will not lose any of the values. See below for the math.
10000
0
200
20
1
=====
10221
Others have pointed out that multiplying b by 1000 shouldn't cause a problem - but if a were zero, you'd end up losing it. (You'd get a 4 digit string instead of 5.)
Here's an alternative (general purpose) approach - which assumes that all the values are in the range 0-9. (You should quite possibly put in some code to throw an exception if that turns out not to be true, but I've left it out here for simplicity.)
public static String concatenateDigits(int... digits)
{
char[] chars = new char[digits.length];
for (int i = 0; i < digits.length; i++)
{
chars[i] = (char)(digits[i] + '0');
}
return new String(chars);
}
In this case you'd call it with:
String result = concatenateDigits(a, b, c, d, e);
For fun... how NOT to do it ;-)
String s = Arrays.asList(a,b,c,d,e).toString().replaceAll("[\\[\\], ]", "");
Not that anyone would really think of doing it this way in this case - but this illustrates why it's important to give access to certain object members, otherwise API users end up parsing the string representation of your object, and then you're stuck not being able to modify it, or risk breaking their code if you do.
Using Java 8 and higher, you can use the StringJoiner, a very clean and more flexible way (especially if you have a list as input instead of known set of variables a-e):
int a = 1;
int b = 0;
int c = 2;
int d = 2;
int e = 1;
List<Integer> values = Arrays.asList(a, b, c, d, e);
String result = values.stream().map(i -> i.toString()).collect(Collectors.joining());
System.out.println(result);
If you need a separator use:
String result = values.stream().map(i -> i.toString()).collect(Collectors.joining(","));
To get the following result:
1,0,2,2,1
Edit: as LuCio commented, the following code is shorter:
Stream.of(a, b, c, d, e).map(Object::toString).collect(Collectors.joining());
int number =0;
int[] tab = {your numbers}.
for(int i=0; i<tab.length; i++){
number*=10;
number+=tab[i];
}
And you have your concatenated number.
I would suggest converting them to Strings.
StringBuilder concatenated = new StringBuilder();
concatenated.append(a);
concatenated.append(b);
/// etc...
concatenated.append(e);
Then converting back to an Integer:
Integer.valueOf(concatenated.toString());
Use StringBuilder
StringBuilder sb = new StringBuilder(String.valueOf(a));
sb.append(String.valueOf(b));
sb.append(String.valueOf(c));
sb.append(String.valueOf(d));
sb.append(String.valueOf(e));
System.out.print(sb.toString());
People were fretting over what happens when a == 0. Easy fix for that...have a digit before it. :)
int sum = 100000 + a*10000 + b*1000 + c*100 + d*10 + e;
System.out.println(String.valueOf(sum).substring(1));
Biggest drawback: it creates two strings. If that's a big deal, String.format could help.
int sum = a*10000 + b*1000 + c*100 + d*10 + e;
System.out.println(String.format("%05d", sum));
You can Use
String x = a+"" +b +""+ c+""+d+""+ e;
int result = Integer.parseInt(x);
Assuming you start with variables:
int i=12;
int j=12;
This will give output 1212:
System.out.print(i+""+j);
And this will give output 24:
System.out.print(i+j);
Best solutions are already discussed.
For the heck of it, you could do this as well:
Given that you are always dealing with 5 digits,
(new java.util.Formatter().format("%d%d%d%d%d", a,b,c,d,e)).toString()
I am not claiming this is the best way; just adding an alternate way to look at similar situations. :)
NOTE: when you try to use + operator on (string + int) it converts int into strings and
concatnates them !
so you need to convert only one int to string
public class scratch {
public static void main(String[] args){
int a=1;
int b=0;
int c=2;
int d=2;
int e=1;
System.out.println( String.valueOf(a)+b+c+d+e) ;
}
//Here is the simplest way
public class ConcatInteger{
public static void main(String[] args) {
int [] list1={1,2,3};
int [] list2={1,9,6};
String stNum1="";
String stNum2="";
for(int i=0 ; i<3 ;i++){
stNum1=stNum1+Integer.toString(list2[i]); //Concat done with string
}
for(int i=0 ; i<3 ;i++){
stNum2=stNum2+Integer.toString(list1[i]);
}
int sum= Integer.parseInt(stNum1)+Integer.parseInt(stNum2); // Converting string to int
System.out.println(sum);
}
}
Couldn't you just make the numbers strings, concatenate them, and convert the strings to an integer value?
public class joining {
public static void main(String[] args) {
int a=1;
int b=0;
int c=2;
int d=2;
int e=1;
String j = Long.toString(a);
String k = Long.toString(b);
String l = Long.toString(c);
String m = Long.toString(d);
String n = Long.toString(e);
/* String s1=Long.toString(a); // converting long to String
String s2=Long.toString(b);
String s3=s2+s1;
long c=Long.valueOf(s3).longValue(); // converting String to long
*/
System.out.println(j+k+l+m+n);
}
}

Categories

Resources