How to convert char 'A' to binary '1010' in java language - java

I want to convert character type to binary but not char byte to bit.
I'll show you example.
if char = 'A' but actually it's hex! A = 1010
I have a character type but I want to represent it like hexadecimal.
Of course, I have only character data that can be matched hexadecimal.
like 9, 8, A, C, D not 47, U, Y ..
And Can I count size or length of 1 in 1010 ?
If you know how to solve this please let me know thank you!

Simple Steps
Here you can convert any Alphabet to the binary number
System.out.println(Long.toString(Long.parseLong("A", 16), 2)); //Output 1010
Thanks

You can most easily (and probably most efficiently) use Character.digit().
int a = Character.digit('A', 16);
System.out.println(Integer.toBinaryString(a));

Since the input is a char, convert using the helper method from Character:
int num = Character.getNumericValue(ch);
Then convert it to a binary string:
String s = Integer.toBinaryString(num);

Related

Putting my 32 bits into a 4 bytearray

I am putting different binary numbers into a byte array. One of the numbers are: 10001101010010010000000000001000 this number is giving me a NumberFormatException on the line where I try to parse it, obviously because it's too big. See code below where string is the binary number.
int number = Integer.parseInt(string, 2);
ByteBuffer bytes = ByteBuffer.allocate(4).putInt(number);
byte[] byteInstruction = bytes.array();
What I want is to put the numbers in my byte array but as they are 32-bit numbers I don't want to take up more than 4 bytes in my array. When I use long to parse it works but then I take up 8 spaces in my byte array.
long number = Long.parseLong(string, 2);
ByteBuffer bytes = ByteBuffer.allocate(8).putLong(number);
byte[] byteInstruction = bytes.array();
If I print out the array later I get this:
[0, 0, 0, 0, -115, 73, 0, 8]
where we can see that there are 4 spots free. How can I solve this? How did I mess up?
All help is appreciated.
Your input string "10001101010010010000000000001000" represents value that is too big for signed Integer. Integer.MAX_VALUE = 2147483647 and the input string you've passed has a value of 2370371592.
The Integer.parseInt does not interpret the leading 1 at position 32 from right as sign. If you would like parse a negative value it would have to be preceded with - sign.
See this answer for more through explanation.
If you expect the input "10001101010010010000000000001000" to in fact mean "-0001101010010010000000000001000" just replace the first character with +/- depending on the value of 32 bit from right.
Alternatively if you would like to treat the binary string in Two's complement compatible way you can use approach from this answer:
int msb = Integer.parseInt("1000110101001001", 2);
int lsb = Integer.parseInt("0000000000001000", 2);
int result = msb<<16 | lsb;

Output of System.out.println( m[1]+` ยด+m[ 2]) [duplicate]

To my understanding a char is a single character, that is a letter, a digit, a punctuation mark, a tab, a space or something similar. And therefore when I do:
char c = '1';
System.out.println(c);
The output 1 was exactly what I expected. So why is it that when I do this:
int a = 1;
char c = '1';
int ans = a + c;
System.out.println(ans);
I end up with the output 50?
You're getting that because it's adding the ASCII value of the char. You must convert it to an int first.
Number 1 is ASCII code 49. The compiler is doing the only sensible thing it can do with your request, and typecasting to int.
You end up with out of 50 because you have told Java to treat the result of the addition as an int in the following line:
int ans = a + c;
Instead of int you declare ans as a char.
Like so:
final int a = 1;
final char c = '1';
final char ans = (char) (a + c);
System.out.println(ans);
Because you are adding the value of c (1) to the unicode value of 'a', which is 49. The first 128 unicode point values are identical to ASCII, you can find those here:
http://www.asciitable.com/
Notice Chr '1' is Dec 49. The rest of the unicode points are here:
http://www.utf8-chartable.de/
A char is a disguised int. A char represents a character by coding it into an int. So for example 'c' is coded with 49. When you add them together, you get an int which is the sum of the code of the char and the value of the int.
'1' is a digit, not a number, and is encoded in ASCII to be of value 49.
Chars in Java can be promoted to int, so if you ask to add an int like 1 to a char like '1', alias 49, the more narrow type char is promoted to int, getting 49, + 1 => 50.
Note that every non-digit char can be added the same way:
'a' + 0 = 97
'A' + 0 = 65
' ' + 0 = 32
'char' is really just a two-byte unsigned integer.
The value '1' and 1 are very different. '1' is encoded as the two-byte value 49.
"Character encoding" is the topic you want to research. Or from the Java language spec: http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.1

10bit binary number from a string to a byte

Currently I have a 8 bit binary string and I want to shift it left and get a 10bit binary number from it.
(ie 0111001010)
String[] channels = datArray.get(n).split(" ");
byte[] RI = channels[m+1].getBytes();
String s = (Integer.toBinaryString(Integer.parseInt(channels[m+1])));
Example Values:
RI is equal to: [B#4223b758
S is equal to: 1100101
Any help is much appreciated.
Wouldn't this work for you:
String input = "1100101";
int value = Integer.parseInt(input, 2) << 1;
System.out.println(Integer.toBinaryString(value));
Returns:
11001010
Parsed binary string and shifted left (one digit).
The two things that it looks like you are missing from your approach are the ability to specify a radix when parsing a String representing a binary numeral, and the left shift operator.
If you wanted the leading zeros I was surprised to see that there is no built in way to accomplish this, and the current wisdom is this is the optimal way (taken from this discussion)
System.out.println(String.format("%10s", Integer.toBinaryString(value)).replace(' ', '0'));
Which for the example value given would return this:
0011001010
You can use following:
BigInteger i = new BigInteger("00000011" + "00", 2);
int x = i.intValue();
Where "00000011" is your string representation of 8 bit number. The "00" simulates the left shifting..

Java Hexa Complement

How does one obtain the complementary hexadecimal value for a given input ?
This could be a bit more generic, i.e. having an array of X possible values, how do you convert a random array like arr[x] --> arr[arr.length - arr.indexOf(x)].
Please ignore the syntax.
The following code snippet will find 16 complement of hexadecimal number:
BigInteger subtrahend = new BigInteger("2D", 16);
// input, you can take input from user and use after validation
char[] array = new char[subtrahend.toString(16).length()];
// construct a character array of the given length
Arrays.fill(array, 'F');
// fill the array by F, look at the first source there the FF is subtracted by 2D
BigInteger minuend = new BigInteger(new String(array), 16);
// construct FFF... Biginteger of that length
BigInteger difference = minuend.subtract(subtrahend);
// calculate minus
BigInteger result = difference.add(BigInteger.ONE);
// add one to it
System.out.println(result.toString(16));
// print it in hex format
Hope this will help you. Thank you.
Source:
Binary and Hexadecimal Arithmetic
Digital Principles and Logic Design
First find the 15's complement of the given input by subtracting it from the number FF... which is of the same length of the input. Then add 1 to it.

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