im an absolute beginner and have following task that I need to complete but im totally confused and can't find anything online, hope someone can help out.
Task:
Let the variable “pattern” be declared as an integer with 32 bits and
initialised with the bit pattern 0011 1101 0101 1110 0101 1111 0001
1010 (3D5E 5F1A). Print the variable, set Bit 7 to 1 and print again.
Given:
int pattern = ;
boolean ww = false;
int value = 0;
System.out.println("bitpattern = " + pattern + " --> " +Integer.toBinaryString(value));
When I understand that right, an integer is by default declared with 32bit so nothing to do for me for this part. But when I try to assign the number 0011 1101 0101 1110 0101 1111 0001 1010 to the "int pattern" I get the error "integer number too large".
where is my misconception ? Does anyone know a tutorial for that?
Thanks
You can do it like this. The underscores are not required but make it easier to separate nibbles. Prefix the string with 0b.
int a = 0b0011_1101_0101_1110_0101_1111_0001_1010;
System.out.println(Integer.toHexString(a));
prints
3d5e5f1a
If you have a String of bits you can do
String bitStr = "00111101010111100101111100011010";
int v = Integer.parseInt(bitStr, 2);
System.out.println(Integer.toHexString(v));
prints
3d5e5f1a
For longs you must suffix with an L
long longbits = 0b0011110101011110010111110001101000111101010111100101111100011010L;
here are other prefixes available
int hex = 0x2A; // prefix with 0x - 42 in decimal
int octal = 023 // prefix with 0 - 19 in decimal
If you had your input in string-form, you could use Integer.parse(input, 2) see docs.
In your case you could so that: value = Integer.parseInt(String.valueOf(pattern), 2) (enclosed in try catch)
Related
I'm looking at parsing information from a temp/humidity sensor that was provided with the following instructions;
There are 6 bytes.
Temperature positive/negative: 0 means positive (+) and 1 means negative (-)
Integer part of temperature. Show in Hexadecimal.
Decimal part of temperature. Show in Hexadecimal.
Reserved byte. Ignore it.
Integer part of humidity. Show in Hexadecimal.
Decimal part of humidity. Show in Hexadecimal.
For example: 00 14 05 22 32 08 means +20.5C 50.8% & 01 08 09 00 14 05
means -8.9C 20.5%
as each byte is in hex & i need to covert this to an Int I followed this approach - Java code To convert byte to Hexadecimal but the values I get when validating their example don't make sense.In Kotlin I do;
val example = byteArrayOf(0, 14, 5, 22, 32, 8)
example.map { Integer.parseInt(String.format("%02X ", it),16)}
First Example output is;
0 = "00 "
1 = "08 "
2 = "09 "
3 = "00 "
4 = "0E "
5 = "05 "
Second Example output;
0 = "00 "
1 = "0E "
2 = "05 "
3 = "16 "
4 = "20 "
5 = "08 "
What am I doing wrong? I'm starting to think the manufactures instructions could be 'misleading'
A key thing you are missing here is that when passing in the it parameter to String#format, that value is a decimal int, not a hexadecimal int.
You instead want to map the value in the array directly to a string, then get its decimal value:
byte it = 14;
int x = Integer.parseInt(String.valueOf(it), 16);
System.out.println(x); // This will print 20
This should get you the expected result.
Note, your problem is slightly confusing because the numbers in your byte array are decimal numbers...already in their hex 'format'. There are a few ways this confusion can be fixed (assuming you have control of the array's type and/or contents):
Use String instead of byte
String it = "14";
int x = Integer.parseInt(it, 16);
System.out.println(x); // This will print 20
Store the values as hex and still convert (i.e., putting a 0x in front of each number)
byte it = 0x14;
int x = Integer.parseInt(String.format("%02X", it), 16);
System.out.println(x); // This will print 20
Store the values as hex and don't convert, because there is no need
byte it = 0x14;
System.out.println(it); // This will print 20
If you go with the second bullet, though convoluted, what you have right now should work, but the third option would be best if you are hardcoding in the byte array's values.
This question already has answers here:
Calculating with the char variable in java
(2 answers)
Closed 4 years ago.
I'm looking for an explanation for Java's behavior when handling the following scenarios. I understand that the ASCII table is arranged so that the value of the character 5 is five positions greater than 0. This allows for calculations to be done on the char without converting to an int as seen in the first example.
What I don't understand is why Java seems to inconsistently handle when to provide a value from an ASCII table and when to do a calculation on the chars as though they were integers.
int x = '5' - '0';
output x = 5;
int x = '5'
output x = 53;
Now for some examples, that introduce confusion.
int x = '0' + 1 - '5'
output x = -4
int y = '5' - '0' + '1'
output 54
int y = '5' - 0 + '1'
output 102
Java seems to be doing an implicit type conversion, but how is Java inferring which representation of the int/char should it be using?
Just write the char conversion to ASCII code (below your statements)
int x = '0' + 1 - '5'
48 + 1 - 53 = -4
int y = '5' - 0 + '1'
53 - 0 + 49 = 102
int y = '5' - '0' + '1'
53 - 48 + 49 = 54
Notice it's consistent, each int remains int and each char converted to ASCII code
This might seem to be inconsistent but in real they are consistent.
int x = '5' - '0';
output x = 5; because behind the back ASCII codes are, '5'=53 and '0'=48.
Hence
int x = '5'
output x = 53;
You might be mixing the representation from the value. The values never change, so when you perform arithmatic it will always be that '5'==53 and not 5. For the display JLS on primitive to string conversion.
Integer arithmetic is promoted to int for most calculations.
System.out.println('5' + '0');
>>> 101
System.out.println((char)('5' + '0'));
>>> e
Both results have the same numeric value, but one is displayed as a character because it has been cast to character.
Java seems to be doing an implicit type conversion, but how is Java inferring which representation of the int/char should it be using?
It's actually quite simple. char is one of the numeric types in Java, see 4.2.1. Integral Types and Values:
The values of the integral types are integers in the following ranges:
[...]
For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535
All operations on integer types are carried out either with int- or long- precision, see 4.2.2. Integer Operations:
If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).
Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.
Note the last sentence: this defines the conversion to be applied, it is called "numeric promotion".
char '0' does not equals int 0. char '0''s binary representation occupies 16 bit:
0000 0000 0011 0000
while int 0's binary representation occupies 32 bit:
0000 0000 0000 0000 0000 0000 0000 0000
When you sum a char and an int, the char will be promoted to int first.
For example. char 5's unicode is 0035, in binary 0000 0000 0011 0101, it will be promoted to int by inserting 16 zeros at head, 0000 0000 0000 0000 0000 0000 0011 0101, and the int represents 53 in decimal.
I have the following code:
int a=-12;
char b=(char) a;
System.out.println(b);
System.out.println(b+0);
It first prints out some empty character and then a number 65524. If I change a to, say, 16 the displayed number becomes 65520. If a is -2, the number is 65534.
If the number is positive and small enough it prints out characters out of Unicode table and returns the character's number (which is the same as a) if everything is OK and that previous strange number from above if it's not allright (if a is too big).
For instance, for a = 8451 it returns ℃ (Degree Celsius) character and a itself (8451), but if a=84510 it returns some strange Chinese symbol and a different from a number (18974). If a is even bigger a=845100 it returns empty sumbol and 58668.
The question is, where do those numbers come from?
I've tried to find the answer, but wasn't lucky so far.
EDIT Since int to char is a narrowing conversion, please consider the same question with byte a. Too large numbers are obviously impossible now, but I wonder what happens with negatives - converting byte a = -x to char gives the same weird numbers as with int a.
int is a signed number which has 4 bytes and 32 bits. The Two's complement representation of -12 is
11111111 11111111 11111111 11110011 .
char is a unsigned which has 2 bytes and 16 bits.
int a=-12;
char b=(char)a;
Two's complement representation of b is
11111111 11110011
which is equivalent to 65524
I think it's because char in Java is an unsigned "Double Byte" integer. When Byte is 8-bits, double-byte is 16-bits = 2 power by 16 = 65536 And you get Two's complement (Binary subtraction operation).
Because the number is unsigned all 16 bits are used to represent the integer, so when you give a negative number it creates an overflow you get the number which is (65536 + a), for example:
When int a = -16; you get 65536 - 16 = 65520(in binary: 1111 1111 1111 0000)
When int a = -2; you get 65536 - 2 = 65534 (in binary: 1111 1111 1111 1110)
When int a = 84510; you exceed the limit of 65536 for char, so you are left with 18974 (84510 - 65536 = 18974).
You get a character from the Unicode table, I guess because it's the character set or code page you defined.
When you cast you should pay attention to the range of values of the data types you cast, in this case, the difference between int and char.
public class bitwise_operator {
public static void main(String[] args) {
int var1 = 42;
int var2 = ~var1;
System.out.println(var1 + " " + var2);
}
}
The above code produces 42 -43 as the output.
As far as my understanding goes, Unary Not operator (~), inverts all of the bits of its operand.
Now, 42 in binary is 00101010. On using ~ operator, we get inverted value of 42 i.e. 11010101
If you convert the preceding binary value, the output should be something else and not -43
Tried my luck with different numbers to observe the pattern and found that, the output is 1 number more than the initial value supplied with a leading (-) sign before it, as seen in the above case.
For eg..,
if num is 45 // Output is 45 -46
if num is 1001 // Output is 1001 -1002
Could someone please explain how the Unary Not Operator (~) works internally to output such results?
You are using a signed integer value which is in 2's complement.
Your result is correct: 11010101 is in fact -43:
-2^7 + 2^6 + 2^4 + 2^2 + 2^0 = -128 + 64 + 16 + 4 + 1 = -128 + 85 = -43
This is what's known as two's complement, and it is how integers and all fixed point numbers in Java, C, C++ etc work
-x = ~x + 1
So for example -1 (0xFFFF) negated bitwise (0x0) plus 1 = 0x1
I have been working on a project and i saw some references on web and they initialized :
int val= 0x000; output 0
int val1= 0x001; output 1
How exactly java is converting this?
Thanks
It's an hexadecimal (base 16 instead of base 10). Hexadecimals starts with 0x.... And it can contain these digits: 0123456789ABCDEF
Octals (base 8) starts with 0... and can containt digits less than 8 (01234567)
int dec = 123; // decimal: 1*(10^2) + 2*(10^1) + 3*(10^0) = 123
int oct = 0123; // octal: 1*(8^2) + 2*(8^1) + 3*(8^0) = 83
int hex = 0x123; // hexadecimal: 1*(16^2) + 2*(16^1) + 3*(16^0) = 291
You can do int val = 0; and int val = 1; with decimal notation..
The 0x before the number indicate an hexadecimal notation...
All notations are:
0b to binary: int i = 0b10101010110;
nothing to decimal: int i = 123;
0 to octal: int i = 0123345670;
0x to hexadecimal: int i = 0xAEF123;
As a matter of fact, Java does not "convert" but "interpret" the values (as hexadecimal).
Numbers starting with 0x are hexadecimal. Java converts them (like decimal ones, too) to binary and saves them.
This hexadecimal number system (base 16)
Start with 0x...
(Octals start with 0...)
Link