Why does 11010100 << 1 equal 110101000, not 10101000? - java

Why when I try to shift bits for 110101002, the result is 1101010002, not 101010002.
int a = Integer.parseInt("11010100", 2) << 1;
I try to do this:
int a = (byte)(Integer.parseInt("11010100", 2) << 1);
But if the output value is greater than 128, everything goes into minus, which is logical.
How can I make that number of bits does not change?

Let's take it one step at a time.
Integer.parseInt("11010100", 2) - this is the int value 212. This is, by the way, needless; you can just write: 0b11010100.
0b11010100 << 1 is the same as 0b110101000, and is 424.
You then cast it to a byte: (byte)(0b11010100 << 1). The bits beyond the first 8 all get lopped off, which leaves 0b10101000, which is -88. Minus, yes, because in java bytes are signed.
You then silently cast this -88 back up to int, as you assign it to an int value. It remains -88, which means all the top bits are all 1s.
Hence, the final value is -88.
If you want to see 168 instead (which is the exact same bits, but shown unsigned instead of signed), the usual trick is to use & 0xFF, which sets all bits except the first 8 to 0, thus guaranteeing a positive number:
byte b = (byte) (0b11010100 << 1);
System.out.println(b); // -88. It is not possible to print 168 when printing a byte.
int asUnsigned = b & 0xFF;
System.out.println(asUnsigned); // 168.
// or in one go:
System.out.println(((byte) (0b11010100 << 1)) & 0xFF); // 168

If you want to set to 0 all bits higher than the bottom 8 bits, you can use bit-wise AND:
int a = (Integer.parseInt("11010100", 2) << 1) & 0xff;
System.out.println (Integer.toString(a,2));
Output:
10101000

Try something like this:
int anInt = Integer.parseInt("11010100", 2) << 1;
int asUnsignedInt= Byte.toUnsignedInt((byte) anInt);
toUnsignedInt has been introduced in Java SE 8.

Related

Reading Little Endian – LS Byte first for integer how to ignore the extra 0

I have been reading these byte by bytes from streams. Example I read this line like this.
int payloadLength = r.readUnsignedShort();
The problem I have is that 2 bytes value is x3100 so it turns out to be 12544 but I suppose to only read as x31 which makes it to be only 49. How to ignore the extra 00.
Right shift the value by 8 bits and then and it with 0xFF. Right shifting moves the bits 8 bits to the right. Any other bits would also be moved to the right so you need to mask those of by do an ANDing (&) with 0xFF to get rid of them.
int payloadLength = r.readUnsignedShort();
payloadLength = (payloadLength >>> 8)& 0xFF;
System.out.println(payLoadLength);
You may also want to swap the two bytes.
v = 0xa0b;
v = swapBytes(v);
System.out.println(Integer.toHexString(v)); // 0xb0a
public static int swapBytes(int v) {
return ((v << 8)&0xFF00) | ((v >> 8) & 0xFF);
}
Normally, for reading in just 16 bits you would not have to and it with 0xFF since the high order bits are 0's. But I think it is a good practice and will prevent possible problems in the future.

Getting value from MSB of 16 bit register

I have 16 bits register which contain some values in LSB and MSB:
LSB:
At bit 0...1 the value is 0
At bit 2 the values is 0
MBS:
At MSB I need to write value 20
So the value that should be written in register is 0 + 0 + 20 = 160
When I'm reading register the I'm doing it on this way:
for the 1st value in bit [0...1]:
firstVal = (valFromReg & (((1 << 2)-1) << 1) / 2)
secondVal = (valFromReg & 4) / 4
But how to read/convert the third value to get number 20?
In Java, a short is a (signed) 16-bit value. You want to split that into 3 values:
Value a is a 2-bit value in bits 0-1
Value b is a 1-bit value in bit 2
Value c is a 13-bit value in bits 3-15
Bit-wise, that can be represented like this: cccc cccc cccc cbaa
To extract the 3 values from the 16-bit reg value, you'd do this:
short reg = /*register value*/;
int a = reg & 0x0003;
int b = (reg >> 2) & 0x0001;
int c = (reg >> 3) & 0x1fff;
To go the other way, you'd do this:
short reg = (short)((c << 3) | (b << 2) | a);
This of course assumes that the values are within value range, i.e. a = 0-3, b = 0-1, and c = 0-8191.
Some things in the question are not quite clear for me...
like:
At MSB I need to write value 20
back in my times MSB was only 1 bit and was only possible to write true or false...
anyways...
A 16 bits signal fits pretty good in an integer...
so you could basically get that register and manipulate it as an integer, then representing that as a binary number AS STRING will lets you to get the MSB or even the bit at any wanted position...
Do this:
Example
int register = -128;
String foo = String.format("%16s", Integer.toBinaryString(register)).replace(' ', '0');
System.out.println(register);
System.out.println(foo);
System.out.println(foo.charAt(0)); //char at 0 is the MSB....

bitwise right shift and 0xFF | Java

I am trying to understand a piece of code but not able to get clear idea about few points
here is the Java code
private String firstMethod(int number){
return secondMethod(number >> 16 & 0xFF, 0).concat(secondMethod(number >> 8 & 0xFF, 1)).concat(secondMethod(number & 0xFF, 7));
}
private static String secondMethod(int value, int offset)
{
return thirdMethod(value >> 4, offset).concat(thirdMethod(value & 0xF, offset + 4));
}
private static String thirdMethod(int value, int offset)
{
String chars = getAlphabet();
int pos = (value + offset) % 16;
return chars.substring(pos, pos + 1);
}
value passed to firstMethod is a random number for first time and all subsequent call to method will pass value incremented by 1.
I am clear about bit-wise right shift operation as well about the use of & 0xFF, however I am still not very clear about following points
Shifting given value by specific number (like 16 and 8 for first than no sift etc)
Not clear about use of offset ,specifically passing certain number as offset.
Can anyone help me to understand those 2 point
Shifting given value by specific number (like 16 and 8 for first than no sift etc)
You are printing bytes as hexi-decimal. Each byte is 8-bits so you want to shift each byte by
Not clear about use of offset ,specifically passing certain number as offset.
I am pretty sure the offset is either a) incorrect, b) a really obscure way of masking/encoding the data.
To print a number as a 6 byte hexi-decimal String you can do this.
System.out.println(String.format("%06x", 12345));
prints
003039
This is much shorter. ;)
>> has a surprising low precedence. This means
number >> 16 & 0xFF
is actually
number >> (16 & 0xFF)
or
number >> 16
what you indedn was
(number >> 16) & 0xFF
or as the result is unsigned.
(number >>> 16) & 0xFF
An integer is a 32-Bit Number.
So as a binary-number, you can represent number as:
XXXXXXXXAAAAAAAABBBBBBBBCCCCCCCC
(X, A, B, C stands for 0 or 1).
number >> 16 gives you XXXXXXXXAAAAAAAA.
number >> 16 & 0xFF gives you AAAAAAAA
By the firstMethod number is splited in 3 Bytes:
AAAAAAAA and BBBBBBBB and CCCCCCC (Shift of 16, shift of 8 and no shift)
and given to the secondMethod.
In the secondMethod the 8 Bits are splited in the higher four bits and the lower four bits.
In the thirdMethod the four Bits is translate to a String containing one char.
But the sense depends on "getAlphabet()".
Perhaps there will be also a usefull interpretation for the offset.
So you have to give further information!

How can I extract a particular bit in Java?

I need a specific bit in a byte value stored as int value. My code is as shown below.
private int getBitValue(int byteVal, int bitShift){
byteVal = byteVal << bitShift;
int bit = (int) (byteVal >>>7);
return bit;
}
It is working when I give the bitshift as 1 but when I give the bitshift as 2 and the byteVal as 67(01000011 in binary), I get the value of 'byteVal' as 268 while 'byteVal' should be 3(000011 in binary) after the first line in the method(the left shift). What am I doing wrong here?
For some reason when I try your code I don't get what you get. For your example, if you say byteVal = 0b01000011 and bitShift = 2, then this is what I get:
byteVal = 0b01000011 << 2 = 0b0100001100
bit = (int) (0b0100001100 >>> 7) = (int) (0b010) // redundant cast
returned value: 0b010 == 2
I believe what you intended to do was shift the bit you wanted to the leftmost position, and then shift it all the way to the right to get the bit. However, your code won't do that for a few reasons:
You need to shift left by (variable length - bitShift) to get the desired bit to the place you want. So in this case, what you really want is to shift byteVal left by 6 places, not 2.
int variables are 32 bits wide, not 8. (so you actually want to shift byteVal left by 30 places)
In addition, your question appears to be somewhat contradictory. You state you want a specific bit, yet your example implies you want the bitShift-th least significant bits.
An easier way of getting a specific bit might be to simply shift right as far as you need and then mask with 1: (also, you can't use return with void, but I'm assuming that was a typo)
private int getBitValue(int byteVal, int bitShift) {
byteVal = byteVal >> bitShift; // makes the bitShift-th bit the rightmost bit
// Assumes bit numbers are 0-based (i.e. original rightmost bit is the 0th bit)
return (int) (byteVal & 1) // AND the result with 1, which keeps only the rightmost bit
}
If you want the bitShift-th least significant bits, I believe something like this would work:
private int getNthLSBits(int byteVal, int numBits) {
return byteVal & ((1 << numBits) - 1);
// ((1 << numBits) - 1) gives you numBits ones
// i.e. if numBits = 3, (1 << numBits) - 1 == 0b111
// AND that with byteVal to get the numBits-th least significant bits
}
I'm curious why the answer should be 3 and I think we need more information on what the function should do.
Assuming you want the value of the byteVal's lowest bitShift bits, I'd do the following.
private int getBitValue(int byteVal, int bitShift){
int mask = 1 << bitShift; // mask = 1000.... (number of 0's = bitShift)
mask--; // mask = 000011111 (number of 1's = bitShift)
return (byteVal & mask);
}
At the very least, this function will return 1 for getBitValue(67, 1) and 3 for getBitValue(67,2).

Issues when converting bytes to integers (Java specific?)

I'm a bit confused regarding a conversion from bytes to integers. Consider the following code:
byte[] data = new byte[] { 0, (byte) 0xF0 };
int masked = data[0] << 8 & 0xFF | data[1] & 0xFF; //240
int notMasked = data[0] << 8 | data[1]; //-16
Because bytes in java are signed, data[1] is not 240 decimal, but rather the 2's complement, -16. However, it should still be, in binary: 0x11110000 so, why do I need to do data[1] & 0xFF ?
Is Java converting everything to Integer before passing it to the | operator? Why does &0xFF make a difference then?
Java bytes are signed (unfortunately) - so when you promote the value to an int in order to perform the bitwise |, it ends up being sign-extended as 0xFFFFFFF0. That then messes up the | with data[0]. The masking with & 0xff converts it to an integer value of 240 (just 0x000000F0) instead.
However, you've stlil got a problem. This code:
int masked = data[0] << 8 & 0xFF | data[1] & 0xFF;
should be:
int masked = ((data[0] & 0xff) << 8) | (data[1] & 0xFF);
... otherwise you're masking after the shift, which won't work. I've added brackets because I'm never sure of the predence of &, << and |...
It is similar to a known "puzzle"
byte x = -1;
x = x >>>= 1;
System.out.println(x);
produces
-1
No shift? This is because before compiling arithemtic / shift / comparison expressions javac promotes byte (as well as short and char) to int or to long (if there is any long in the expression), so it works as follows
x -> int = 0xFFFFFFFF; 0xFFFFFFF >>> 1 = 0x7FFFFFF; (byte)0x7FFFFFF -> 0xFF

Categories

Resources