Match byte patterns - java

Say you are having a byte of pattern:
byte b = 0x%1;
How to tell when a byte does have certain values on the "2nd position" - in place of % ?
In this example 1, no matter what the 1st position holds.

Use a mask bits to get the last 8 bits:
int last8bits = b & 0xF;
Edit: You should read up on bitwise operations.
Full example:
public static void main(String[] args) {
byte b = (byte) 0xA1;
int last8bits = b & 0xF;
if (last8bits == 0x01)
System.out.println("\"matches\"");
}

if ((0x0F & b) == 0x01) {
// pattern matched

Related

How to transform an array with several bytes inside into its translation in int?

Given an array filled with 4 bytes inside (R,G,B,A), I'm trying to translate this array full of 4 8bits numbers into its translation in 32bits. To be more clear, if I get an array such as:
byte[] tab = {1,2,3,4};
with translated in binary in 8bit :
1 = 0b00000001
2 = 0b00000010
3 = 0b00000011
4 = 0b00000100
Then, my method should return a byte array such as :
newTab = {00000001_00000010_00000011_00000100};
For some reason, I'm trying to do this without using a String to concatenate the bytes.
I've already tried something with binary operators such as <<, >> or |, but without success...
So far, my code looks like this :
byte[] tab = {1,2,3,4};
int tmp,tabToInt = 0;
for (int x = 0 ; x < tab.length ; ++x){
tmp = tmp << (tab.length - 1 - x)*8;
byteToInt = byteToInt | tmp;
}
return tabToInt;
But it didn't seem to work, even less with negatives bytes... (like -1 = 0b11111111)
Thanks in advance for your answers!
You can use ByteBuffer like this.
byte[] tab = {1, 2, 3, 4};
int tabToInt = ByteBuffer.wrap(tab).getInt();
System.out.println("decimal = " + tabToInt);
System.out.println("binary = " + Integer.toBinaryString(tabToInt));
System.out.println("hexadecimal =" + Integer.toHexString(tabToInt));
output
decimal = 16909060
binary = 1000000100000001100000100
hexadecimal =1020304
ByteBuffer can do it, but only if you get passed at least 4 bytes.
The problem with your code is two-fold:
I think you typoed somewhere, your code doesn't even compile. I think you meant tmp = tab[x] << (tab.length - 1 - x)*8;. Your snippet never does anything with tab other than ask for its length.
Negative numbers extend, and java will convert any byte or short to an int the moment you do any math to it. So, 0b1111 1111, if you try to do e.g. << 8 on that, java first turns that -1 byte into a -1 int (so that's now 32 1 bits), and then dutifully left shifts it by 8, so now that's 24 1 bits, followed by 8 0 bits. You then bitwise OR that into your target, and thus now the target is mostly 1 bits. To convert a byte to an int without "sign extension", (b & 0xFF does it:
byte b = (byte) 0b1111_1111;
assert b == -1; // yup, it is
int c = b; // legal
assert c == -1; // yeah, still is. uhoh. That's...
int d = 0b11111111_11111111_11111111_11111111;
assert c == d; // yeah. We don't want that.
int e = (b & 0xFF);
assert e = 255;
int f = 0b0000000_0000000_0000000_11111111;
assert e == f; // yes!

Unique hash with maximum of 4 characters?

What is the best method to create a hash of String, if the hash may not have more than 4 characters, and those 4 characters may only be lowercase letters or digits?
The strings I want to hash have 1-255 characters.
I know that it's probably impossible to create as 4-char hash without collision. But it would be sufficient if I'd have a good hash where possible collisions are minimized.
What I tried is the CRC16CCITT from here:
http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java
public class CRC16CCITT {
public static void main(String[] args) {
int crc = 0xFFFF; // initial value
int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
// byte[] testBytes = "123456789".getBytes("ASCII");
byte[] bytes = args[0].getBytes();
for (byte b : bytes) {
for (int i = 0; i < 8; i++) {
boolean bit = ((b >> (7-i) & 1) == 1);
boolean c15 = ((crc >> 15 & 1) == 1);
crc <<= 1;
if (c15 ^ bit) crc ^= polynomial;
}
}
crc &= 0xffff;
StdOut.println("CRC16-CCITT = " + Integer.toHexString(crc));
}
}
But this gives too many collision. Are there better algorithms?
You are mistaking "hexadecimal digits" for "characters":
int crc = 0xFFFF; // initial value
That's only 2 bytes (0xFF is just 1 byte). For a CRC of 4 ANSI characters, you need 4 bytes (0xFFFFFFFF).
You'll have to adapt the rest of the code to work with double the legth, please comment if you don't know how to do that.
PS: You could do it with less than 4 bytes, but that would complicate things more than necessary.

How do you flip a specific bit in a Java primitive byte?

I have never used bytes in Java before, so I am unfamiliar with the sytnax for manipulating bytes and bits. I searched how to do this task, but I can't find a simple solution.
I have a byte b. b has eight bits. I would like to flip the ith bit of b to its negation (0 -> 1, 1 -> 0). How do I do this?
I think this will work:
byte b = 0; // initial val ...0000000
final int theNumberofTheBitToFlip = 2; // bit to flip
b = (byte) (b ^ (1 << theNumberofTheBitToFlip));
System.out.println(b); // result ...0000100 = 8
b = (byte) (b ^ (1 << theNumberofTheBitToFlip));
System.out.println(b);// result ...0000000 = 8
Try this
int i=3;
b = (byte) (b ^ (1 << i));

How to find most significant bit (MSB)

I want to know which value the first bit of a byte has.
For example:
I have byte m = (byte) 0x8C;
How could I know if the first bit is an 1 or a 0 ?
Can anyone help me out ?
It depends what you mean by "first bit". If you mean "most significant bit" you can use:
// 0 or 1
int msb = (m & 0xff) >> 7;
Or if you don't mind the values being 0x80 or 0, just use:
// 0 or 0x80
int msb = m & 0x80;
Or in fact, as a boolean:
// Uses the fact that byte is signed using 2s complement
// True or false
boolean msb = m < 0;
If you mean the least significant bit, you can just use:
// 0 or 1
int lsb = m & 1;
If the first bit is the lowest bit (ie bit 0), then
if((m & 1) >0) ...
should do it.
In general,
if ((m & (1<<N)) > 0) ...
will give you whether or not bit N is set.
If, however, you meant the highest bit (bit 7), then use N=7.
Assuming you mean leftmost bit, bitwise and it with 0x80 and check if it is zero nor not:
public boolean isFirstBitSet(byte b) {
System.out.println((b & (byte)0x80));
return (b & (byte)0x80) < 0;
}
If you mean lowest order bit you will need to and with 0x01 and check a different condition:
public boolean isFirstBitSet(byte b) {
System.out.println((b & (byte)0x01));
return (b & (byte)0x80) > 0;
}
Use the bitwise and operator.
public class BitExample {
public static void main(String args[]) throws Exception {
byte m = (byte)0x8C;
System.out.println("The first bit is " + (m & (byte)0x01));
m = (byte)0xFF;
System.out.println("The first bit is " + (m & (byte)0x01));
}
}
// output is...
The first bit is 0
The first bit is 1
Its a bit of a hack but you can use
if(x >> -1 != 0) // top bit set.
This works for byte, short, int, long data types.
However for most types the simplest approach is to compare with 0
if (x < 0) // top bit set.
This works for byte, short, int, long, float, or double
(Ignoring negative zero and negative NaN, most people do ;)
For char type you need to know the number of bits. ;)
if (ch >>> 15 != 0) // top bit set.
This code gives you msb(most significant bit)/biggest number which is a
power of 2 and less than any given number.
class msb{
void main(){
int n=155;//let 110001010
int l=(Integer.toBinaryString(n)).length();//9
String w="0"+Integer.toBinaryString(i).substring(1);//010001010
i=Integer.parseInt(w,2);
System.out.println(n^i);//110001010^010001010=100000000
}
}

Java: Checking if a bit is 0 or 1 in a long

What method would you use to determine if the the bit that represents 2^x is a 1 or 0 ?
I'd use:
if ((value & (1L << x)) != 0)
{
// The bit was set
}
(You may be able to get away with fewer brackets, but I never remember the precedence of bitwise operations.)
Another alternative:
if (BigInteger.valueOf(value).testBit(x)) {
// ...
}
I wonder if:
if (((value >>> x) & 1) != 0) {
}
.. is better because it doesn't matter whether value is long or not, or if its worse because it's less obvious.
Tom Hawtin - tackline Jul 7 at 14:16
You can also use
bool isSet = ((value>>x) & 1) != 0;
EDIT: the difference between "(value>>x) & 1" and "value & (1<<x)" relies on the behavior when x is greater than the size of the type of "value" (32 in your case).
In that particular case, with "(value>>x) & 1" you will have the sign of value, whereas you get a 0 with "value & (1<<x)" (it is sometimes useful to get the bit sign if x is too large).
If you prefer to have a 0 in that case, you can use the ">>>" operator, instead if ">>"
So, "((value>>>x) & 1) != 0" and "(value & (1<<x)) != 0" are completely equivalent
For the nth LSB (least significant bit), the following should work:
boolean isSet = (value & (1 << n)) != 0;
You might want to check out BitSet: http://java.sun.com/javase/6/docs/api/java/util/BitSet.html
Bit shifting right by x and checking the lowest bit.
In Java the following works fine:
if (value << ~x < 0) {
// xth bit set
} else {
// xth bit not set
}
value and x can be int or long (and don't need to be the same).
Word of caution for non-Java programmers: the preceding expression works in Java because in that language the bit shift operators apply only to the 5 (or 6, in case of long) lowest bits of the right hand side operand. This implicitly translates the expression to value << (~x & 31) (or value << (~x & 63) if value is long).
Javascript: it also works in javascript (like java, only the lowest 5 bits of shift count are applied). In javascript any number is 32-bit.
Particularly in C, negative shift count invokes undefined behavior, so this test won't necessarily work (though it may, depending on your particular combination of compiler/processor).
How does it work?
The cleverness of this answer lies in that the sign bit of an integer is very easy to read: when that bit is set, then the value is negative; if not set, then the value is either zero or positive.
So the whole idea is to shift the xth bit exactly into the sign bit. That means a displacement of 31 - x to the left (or 63 - x, if value is 64 bits wide).
In java (and other languages as well), the ~ operator computes the bitwise NOT operation, which arithmetically equals to -x - 1 (no matter how wide x is).
Also the java << operator takes only the least significant 5 (or 6) bits of the right-hand side operand (whether 5 or 6 depends on how wide the left-hand side operand is: for int then 5; for long then 6). Arithmetically this is the same as the remainder of division by 32 (or 64).
And that is (-x - 1) % 32 = 31 - x (or (-x - 1) % 64 = 63 - x, for 64 bit wide value).
The value of the 2^x bit is "variable & (1 << x)"
My contribution - ignore previous one
public class TestBits {
public static void main(String[] args) {
byte bit1 = 0b00000001;
byte bit2 = 0b00000010;
byte bit3 = 0b00000100;
byte bit4 = 0b00001000;
byte bit5 = 0b00010000;
byte bit6 = 0b00100000;
byte bit7 = 0b01000000;
byte myValue = 9; // any value
if (((myValue >>> 3) & bit1 ) != 0) { // shift 3 to test bit4
System.out.println(" ON ");
}
}
}
If someone is not very comfortable with bitwise operators, then below code can be tried to programatically decide it. There are two ways.
1) Use java language functionality to get the binary format string and then check character at specific position
2) Keep dividing by 2 and decide the bit value at certain position.
public static void main(String[] args) {
Integer n =1000;
String binaryFormat = Integer.toString(n, 2);
int binaryFormatLength = binaryFormat.length();
System.out.println("binaryFormat="+binaryFormat);
for(int i = 1;i<10;i++){
System.out.println("isBitSet("+n+","+i+")"+isBitSet(n,i));
System.out.println((binaryFormatLength>=i && binaryFormat.charAt(binaryFormatLength-i)=='1'));
}
}
public static boolean isBitSet(int number, int position){
int currPos =1;
int temp = number;
while(number!=0 && currPos<= position){
if(temp%2 == 1 && currPos == position)
return true;
else{
temp = temp/2;
currPos ++;
}
}
return false;
}
Output
binaryFormat=1111101000
isBitSet(1000,1)false
false
isBitSet(1000,2)false
false
isBitSet(1000,3)false
false
isBitSet(1000,4)true
true
isBitSet(1000,5)false
false
isBitSet(1000,6)true
true
isBitSet(1000,7)true
true
isBitSet(1000,8)true
true
isBitSet(1000,9)true
true
declare a temp int and make it equal the original.
then shift temp >> x times, so that the bit you want to check is at the last position. then do temp & 0xf to drop the preceding bits. Now left with last bit. Finally do if (y & 1 == 0), if last bit is a 1, that should equal 0, else will equal 1. Its either that or if (y+0x1 == 0)... not too sure. fool around and see
I coded a little static class which is doing some of the bit operation stuff.
public final class Bitfield {
private Bitfield() {}
// ********************************************************************
// * TEST
// ********************************************************************
public static boolean testBit(final int pos, final int bitfield) {
return (bitfield & (1 << pos)) == (1 << pos);
}
public static boolean testNum(final int num, final int bitfield) {
return (bitfield & num) == num;
}
// ********************************************************************
// * SET
// ********************************************************************
public static int setBit(final int pos, final int bitfield) {
return bitfield | (1 << pos);
}
public static int addNum(final int number, final int bitfield) {
return bitfield | number;
}
// ********************************************************************
// * CLEAR
// ********************************************************************
public static int clearBit(final int pos, final int bitfield) {
return bitfield ^ (1 << pos);
}
public static int clearNum(final int num, final int bitfield) {
return bitfield ^ num;
}
}
If there are some questions flying around, just write me an email.
Good Programming!
Eliminate the bitshifting and its intricacies and use a LUT for the right and operand.

Categories

Resources