Java convert 16 bits signed to 4 digits hex - java

When dealing with signed int conversion to hex, only Integer.toString(value, 16) is useful
see a post on subject
but I need to format with 4 hex digits (leading zeros for positive numbers and not 32bits/8chars for negatif numbers),
in C++ the right function is IntToHex( value,4)
http://docwiki.embarcadero.com/Libraries/XE3/en/System.SysUtils.IntToHex
But I didn't fiund the equivalent in Java (Android).

Found it :
int StepRef =-2;
String SS = String.format("%08X",StepRef);
String SS4 = SS.substring(SS.length() - 4);

Related

What is the purpose of low and high nibble when converting a string to a HexString

Recently I have been going through some examples of MD5 to start getting an understanding of security and MD5 has been fairly simple to understand for the most part and a good starting point even though it is no longer secure. Despite this I have a question regarding high and lo nibbles when it comes to converting a string to a hex string.
So I know high and low nibbles are equal to half a byte or also can be hex digits that represent a single hexadecimal digit. What I am not understanding though is exactly how they work and the purpose that they serve. I have been searching on google and I can't find much of an answer that will help explain what they do in the context that they are in. Here is the context of the conversion:
private static String toHexString( byte[] byteArray )
{
final String HEX_CHARS = "0123456789ABCDEF";
byte[] result = new byte[byteArray.length << 1];
int len = byteArray.length;
for( int i = 0 ; i < len ; i++ )
{
byte b = byteArray[i]
int lo4 = b & 0x0F;
int hi4 = ( b & 0xF0 ) >> 4;
result[i * 2] = (byte)HEX_CHARS.charAt( hi4 );
result[i * 2 + 1] = (byte)HEX_CHARS.charAt( lo4 );
}
return new String( result );
}
I don't exactly understand what is going on in the for statement. I would appreciate any help understanding this and if there is some link to some places that I can learn more about this please also leave it.
I understand the base definition of nibble but not the operations and what the assignment to the number 4 is doing either.
If I need to post the full example code I will just ask as I am unsure if it is needed.
This code simply converts a byte array to hexadecimal representation. Within the for-loop, each byte is converted into two characters. I think it's easier to understand it on an example.
Assume one of the bytes in your array is, say, 218 (unsigned). That's 1101 1010 in binary.
lo4 gets the lowest 4 bits by AND-ing the byte with the bitmask 00001111:
int lo4 = b & 0x0F;
This results in 1010, 10 in decimal.
hi4 gets the highest 4 bits by AND-ing with the bitmask 1111 0000 and shifting 4 bits to the right:
int hi4 = ( b & 0xF0 ) >> 4;
This results in 1101, 13 in decimal.
Now to get the hexadecimal representation of this byte you only need to convert 10 and 13 to their hexadecimal representations and concatenate. For this you simply look up the character in the prepared HEX_CHARS string at the specific index. 10 -> A, 13 -> D, resulting in 218 -> DA.
It's just bit operations. The & character takes the literal bit value of each and does a logical and on them.
int lo4 = b & 0x0F;
for instance if b = 24 then it will evaluate to this
00011000
+00001111
=00001000
The second such line does the same on the first four bits.
00011000
+11110000
=00010000
the '>>' shifts all of the bits a certain number in that direction so
00010000 >> 4 = 00000001.
This is done so that you can derive the hex value from the number. Since each character in hex can represent 4 bits by splitting the number into pieces of 4 bits we can convert it.
in the case of b = 24 we no have lo4 = 1000 or 8 and hi4 = 0001 or 1. The last part of the loop assigns the character value for each.
Hex_chars[hi4] = '1' and Hex_chars[lo4] = '8' which gives you "18" for that part of the string which is 24 in hex.

Conversion from hex to binary keeping 8 bits in Java

I need to write in a 8x8 matrix the binary values of 8 hexadecimal numbers (one for row). Those numbers will be at the most 8 bits long. I wrote the following code to convert from hexadecimal to binary:
private String hexToBin (String hex){
int i = Integer.parseInt(hex, 16);
String bin = Integer.toBinaryString(i);
return bin;
}
But I have the problem that values below 0x80 don't need 8 bits to be represented in binary. My question is: is there a function to convert to binary in an 8-bit format (filling the left positions with zeros)? Thanks a lot
My question is: is there a function to convert to binary in an 8-bit format (filling the left positions with zeros)?
No, there isn't. You have to write it yourself.
Here's one simple way. If you know the input is always a single byte, then you could add 256 to the number before calling toBinaryString. That way, the string will be guaranteed to be 9 characters long, and then you can just shave off the first character using substring:
String bin = Integer.toBinaryString(256 + i).substring(1);
Hint: use string concatenation to add the appropriate number of zeros in the appropriate place.
For example:
public String hexToBin(String hex) throws NumberFormatException {
String bin = Integer.toBinaryString(Integer.parseInt(hex, 16));
int len = bin.length();
return len == 8 ? bin : "00000000".substring(len - 8) + bin;
}
(Warning: untested ...)
I've concatenated this way. Thanks!
private String hexToBin (String hex){
int i = Integer.parseInt(hex, 16);
String bin = Integer.toBinaryString(i);
while (bin.length()<8){
bin="0"+bin;
}
return bin;
}

applying 2's complement in hex string in java

i have hex value 03E7 which is string in type.i need to apply 2s compliment in this string.and the resultant hex value should be in string format.i first converted it to binary then converted .is there is any simple method?
Negative numbers are the 2's complement of positive numbers and vice versa, so I suppose you could parse your string into an int, multiply by -1, and then parse it back into the resulting hex string.
int intVal = Integer.parseInt("03E7", 16);
String twosComplement = Integer.toHexString((-1 * intVal));

Printing binary values in Java

Why the output of this java program is 8 and 9 while we try to print 010 and 011 respectively:
public class Test{
public static void main(String str[]){
System.out.println(011);
}
}
What is the reason?
In Java, the default conversion from integer to string is base 10. If you want a different radix, you have to specify it explicitly. For instance, you can convert an integer value to a binary string using:
Integer.toString(value, 2);
Similarly, you can convert it to an octal value with:
Integer.toString(value, 8);
Unless the value is 0, the string will not have a leading zero. If you want a leading 0, you'll have to prepend it. Alternatively, you can format it with String.format() and specify zero fill and a minimum width for the converted string:
String.format("%1$03o", value); // the "1$ in the format string is optional here
P.S. It's not clear from your question what the exact problem is. It sounds like it's that you are converting from an integer value to a string. However, if the problem is that you're trying to read the string "011" and it is being read as the integer value 9, this is because a leading 0 forces interpretation as an octal value. You'll have to read it as a String value and then explicitly specify the conversion from string to integer to be base 10:
int val = Integer.valueOf(stringValue, 10);
010 is interpretetion of 10 in octal base which is 8. And similarly 011 is interpretetion of 11 in octal base which is 9.
Prepending an integer with 0 makes it interpreted in octal base.
Similarly, you can try printing 0x10, which is a hexadecimal representation, and will give you 16 as output.
- If you want to convert the integer to binary data, use toBinaryString() method.
Eg:
int i = 8;
Integer.toBinaryString(i);
bec. when you start your number with 0 JVM convert the number from decimal to octal that's all ;)
"11 in decimal = 9 in octal"
decimal 0 1 2 3 4 5 6 7 8 9
octal 0 1 2 3 4 5 6 7 10 11

How to convert a long to a fixed-length 16-bit binary string?

Hi i want to convert a long integer to binary but the problem is i want a fixed 16 bit binary result after conversion like if i convert 2 to 16 bit binary it should give me 0000000000000010 as ans can anyone help me ?
Most likely what you want is Integer.toBinaryString(), combined with something to ensure that you get exactly 16 places:
int val = 2;
String bin = Integer.toBinaryString(0x10000 | val).substring(1);
The idea here is to get the zero padding by putting a 1 in the 17th place of your value, and then use String.substring() to chop off the leading 1 this creates, thus always giving you exactly 16 binary digits. (This works, of course, only when you are certain that the input is a 16-bit number.)
I'm presuming that you want a String output of fixed length (16). Here's what the code would look like:
String binarized = Integer.toBinaryString(i);
int len = binarized.length();
String sixteenZeroes = "00000000000000000";
if (len < 16)
binarized = sixteenZeroes.subString(0, 16-len).concat(binarized);
else
binarized = binarized.subString(len - 16);
return binarized;
Warning: I didn't compile or run it, so make sure no bug is there :)
In contrast to many suggestions here: Integer.toBinaryString, doesn't work for a 16 bit (a short) and it will not print leading zero's. The reason is that (as the name suggests) this will only work for integers. And for negative numbers the bit representation will change (the first bit indicates a negative number). The two numbers below represent the same number in short and int. So if you want to represent the raw bits you have received (this is the general application of your problem), this function will generate strange output.
decimal: -3
short: 1111 1111 1111 1101
int: 1111 1111 1111 1111 1111 1111 1111 1101
EDIT: Changed the number above
Hence you can not cast the short if you are interested in the bit.
Java doesn't provide the implementation for short, so you will have to provide your own. Something like this (size is the number of bits):
int displayMask = 1 << (size - 1);
StringBuffer buf = new StringBuffer( size);
for ( int c = 1; c <= size; c++ )
{
buf.append( ( value & displayMask ) == 0 ? '0' : '1' );
value <<= 1;
}
I had to do it for a 32 bit number and ended up with:
String stringWord = Long.toBinaryString(word);
while (stringWord.length() < 32) // ensure that length of word is 32
stringWord = "0" + stringWord;
Integer.toBinaryString will convert an int to its binary representation as a string.
It does not give you leading zeroes, so if you really need the string to have those and be 16 bits, you can just add them yourself.
You should know how to do that.
Do note that an int is actually 32 bits in Java. You should also know how two's complement works. The binary representation of -1, for example, is 32 1s.
In terms of an algorithm to convert base10 numbers to binary, I personally think the following is pretty straightforward:
char[] array;
for (i; i < 16; i++)
{
if (yourNumber % 2 == 0)
array[16-i] = '0';
else if (yourNumber % 2 == 1)
array[16-i] = '1';
yourNumber = yourNumber / 2;
}
You can then convert your char array to a String if you like.
if you want the binary representation of a long, then there is a method in the Long objet to do so :
String Long.toString(long i, int radix);
with a radix of 2, you should have a binary representation.
regards
Guillaume
Binary is a representation and not a format to convert an integer to. For example, if you have an integer:
int i = 2;
The binary representation will be 00000010. Java has only signed integers, so this link will be helpful.

Categories

Resources