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
Related
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");
}
}
}
Output for converting a number in decimal into its 1s complement and then again converting the number into decimal does not come as expected.
MyApproach
I first converted the number from decimal to binary. Replaced all Os with 1 and vice versa and then converted the number into decimal.
Can anyone guide me? What I am doing wrong?
Code:
public static int complimentDecimal(int num) {
int p = 0;
String s1 = "";
// Convert Decimal to Binary
while (num > 0) {
p = num % 2;
s1 = p + s1;
num = num / 2;
}
System.out.println(s1);
// Replace the 0s with 1s and 1s with 0s
for (int j = 0; j < s1.length(); j++) {
if (s1.charAt(j) == 0) {
s1.replace(s1.charAt(j), '1');
} else {
s1.replace(s1.charAt(j), '0');
}
}
System.out.println(s1);
int decimal = 0;
int k = 0;
for (int m = s1.length() - 1; m >= 0; m--) {
decimal += (s1.charAt(m) * Math.pow(2, k));
k++;
}
return decimal;
}
First of all you need to define the amount of Bits your binary representation should have or an complement representation does not make sense.
If you convert 100 the binary is 1100100
complement is 0011011 which is 27
now convert 27. Binary is 11011, complement 00100 which is 4.
Now define yourself a Bit length of 8.
100 is 01100100, complement 10011011, is 155
155 is 10011011, complement 01100100, is 100
Works because every binary representation has a length of 8 bits. This is absolutly necessary for the whole complement thing to make any sense.
Consider that you now have a limit for numbers that are convertable.
11111111 which is 255.
Now that we talked about that I will correct your code
static int MAX_BITS = 8;
static int MAX_INT = (int)Math.pow(2, MAX_BITS) - 1;
public static int complimentDecimal(int num)
{
// check if number is to high for the bitmask
if(num > MAX_INT){
System.out.println("Number=" + num + " to high for MAX_BITS="+MAX_BITS);
return -1;
}
// Your conversion works!
int p=0;
String s1="";
//Convert Decimal to Binary
while(num>0)
{
p=num%2;
s1=p+s1;
num=num/2;
}
// fill starting zeros to match MAX_BITS length
while(s1.length() < MAX_BITS)
s1 = "0" + s1;
System.out.println(s1);
//Replace the 0s with 1s and 1s with 0s
// your approach on that is very wrong
StringBuilder sb = new StringBuilder();
for(int j=0;j<s1.length();j++){
if(s1.charAt(j)=='0') sb.append("1");
else if(s1.charAt(j)=='1') sb.append("0");
}
s1 = sb.toString();
/*
for(int j=0;j<s1.length();j++)
{
if(s1.charAt(j)==0)
{
s1.replace(s1.charAt(j),'1');
}
else
{
s1.replace(s1.charAt(j),'0');
}
}
*/
System.out.println(s1);
int decimal=0;
int k=0;
for(int m=s1.length()-1;m>=0;m--)
{
// you don't want the char code here but the int value of the char code
//decimal += (s1.charAt(m) * Math.pow(2, k));
decimal+=(Character.getNumericValue(s1.charAt(m))*Math.pow(2, k));
k++;
}
return decimal;
}
Additional Note: Don't get bigger then MAX_BITS = 31 or you need to work with long instead of int in your method.
First of all you have to assign the replaced String to the already defined variable that is,
s1.replace(s1.charAt(j),'1');
it should be
s1 = s1.replace(s1.charAt(j),'1');
and the next case is, when you are changing in that order it would change all the characters similar to matched case
refer Replace a character at a specific index in a string?
String.Replace(oldChar, newChar) method returns a new string resulting from replacing all occurrences of oldChar in given string with newChar. It does not perform change on the given string.
The problem (OK, one of the problems) is here:
if(s1.charAt(j)==0)
Characters in Java are actually integers, in the range 0 to 65535. Each of those numbers actually means the character corresponding to that number in the Unicode chart. The character '0' has the value 48, not 0. So when you've created a string of '0' and '1' characters, the characters will have the integer values 48 and 49. Naturally, when you compare this to the integer 0, you'll get false no matter what.
Try
if(s1.charAt(j)=='0')
(Note: OK, the other answer is right--replace does not work. Not only are you using it incorrectly, by not assigning the result, it's not the right method anyway, because s1.replace(s1.charAt(j),'1') replaces all '0' with '1' characters; it doesn't replace character j. If you specifically want to replace the j'th character in a String with something else, you'll need to use substring() and build a new string, not replace().)
A couple other things to note: (1) Integers are not "decimal" or "binary". When your method gets the num parameter, this is just a number, not a decimal number or a binary number. It's represented in your computer as a binary number (unless you're using something like a Burroughs 3500, but I think all of those died before Java was invented). But it really isn't considered decimal, binary, octal, hex, ternary, or whatever, until you do something that converts it to a String. (2) I know you said not to post alternative approaches, but you could replace the entire method with just one line: return ~num;. That complements all the bits. If you were thinking that you couldn't do this because num was a decimal number, see #1. (3) "Compliment" means to say something nice about somebody. If you're talking about flipping all the bits, the correct spelling is "complement".
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));
String message= "10";
byte[] bytes = message.getBytes();
for (int n = 0; n < bytes.length; n++) {
byte b = bytes[n];
for (int i = 0; i < 8; i++) {//do something for each bit in my byte
boolean bit = ((b >> (7 - i) & 1) == 1);
}
}
My problem here is that it takes 1 and 0 as their ASCII values, 49 and 48, instead of 1 and 0 as binary(00000001 and 00000000). How can I make my program treat each character from my string as a binary sequence of 8 bits?
Basicly, I want to treat each bit of my number as a byte. I do that like this byte b = bytes[n]; but the program treats it as the ASCII value.
I could assign the number to an int, but then, I can't assign the bits to a byte.
It's a bit messy, but the first thing that comes to mind is to first, split your message up into char values, using the toCharArray() method. Next, use the Character.getNumericValue() method to return the int, and finally Integer.toBinaryString.
Example
String message = "123456";
for(char c : message.toCharArray())
{
int numVal = Character.getNumericValue(c);
String binaryString = Integer.toBinaryString(numVal);
for(char bit : binaryString)
{
// Do something with your bits.
}
}
String msg = "1234";
for(int i=0 ; i<msg.length() ; i++ ){
String bits = Integer.toBinaryString(Integer.parseInt(msg.substring(i, i+1)));
for(int j=0;j<8-bits.length();j++)
bits = "0"+bits;
}
Now bits is a string of length 8.
1
00000001
10
00000010
11
00000011
100
00000100
You can use getBytes() on the String
Use Java's parseInt(String s, int radix):
String message= "10";
int myInt = Integer.parseInt(message, 2); //because we are parsing it as base 2
At that point you have the correct sequence of bits, and you can do your bit-shifting.
boolean[] bits = new boolean[message.length()];
System.out.println("Parsed bits: ");
for (int i = message.length()-1; i >=0 ; i--) {
bits[i] = (myInt & (1 << i)) != 0;
System.out.print(bits[i] ? "1":"0");
}
System.out.println();
You could make it bytes if you really want to, but booleans are a better representation of bits...
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