Hex digit to binary with only 4 digits - java

int[] LETTERS = {0x69F99}
I want to convert every single hex digit to binary, for example the 1st hex digit from the 1st hex string (6):
String hex = Integer.toHexString(LETTERS[0]);
String binary = Integer.toBinaryString(hex.charAt(0));
System.out.println(binary);
OUTPUT:110110
If I do this Integer.toBinaryString(6) the output will be 110, but I want something with 4 digits, is it possible?

I'd just pad the string as appropriate with your favorite library or a utility function.
With Guava:
String binary = Strings.padStart(Integer.toBinaryString(hex.charAt(0)), 4, '0'));
Another option would be to simply fill a character buffer and render it as a string, which is essentially what the OpenJDK implementation does:
public static String intToBin(int num) {
char[] buf = new char[4];
buf[0] = num & 0x1;
buf[1] = num & 0x2;
buf[2] = num & 0x4;
buf[3] = num & 0x8;
return new String(buf);
}

You have no string here - just an array with one int so you essentially try to convert this integer into nibbles and this can be done this way:
int num = 0x12345678;
String bin32 = String.format("%32s", Integer.toBinaryString(num)).replace(" ", "0");
System.out.printf("all 32bits=[%s]\n", bin32);
for(int nibble = 0; nibble < 32; nibble += 4)
{
System.out.printf("nibble[%d]=[%s]\n", nibble, bin32.subSequence(nibble, nibble+4));
}
gives:
all 32bits=[00010010001101000101011001111000]
nibble[0]=[0001] ie hex digit 1 as bin
nibble[4]=[0010] ie hex digit 2 as bin
nibble[8]=[0011]
nibble[12]=[0100]
nibble[16]=[0101]
nibble[20]=[0110]
nibble[24]=[0111]
nibble[28]=[1000] ie hex digit 8 as bin

Related

Converting int/long to 64-bit binary

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.

how convert long binary string to character

I have binary string xl and xr
xl = "11110101011100001001011010011100"
xr = "01100101111100011000011000101011"
I want to add xl and xr and convert this binary string to 8 character (1 character = 8 bit). Can you help me to get this code?
String Chippertext = "";
char nextChar;
for(int i = 0; i <= chippertext.length()-8; i += 8) //this is a little tricky. we want [0, 7], [9, 16], etc
{
nextChar = (char)Integer.parseInt(chippertext.substring(i, i+8), 2);
Chippertext += nextChar;
}
Thasil.setText(Chippertext);
I have already try this code but the character doesn't same with the character on ascii table.
You can't use chars to represent the data of a byte array because there are values that are not equivalent to a "char".
The best solution is to print each byte value as decimal, hexadecimal or binary value.

Convert each character of a string in bits

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...

How to convert a hex to a number that looks the same when printed in 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]+"":"");

Integer to two digits hex in Java

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

Categories