Java bit manipulation

Source: Internet
Author: User

In the resolution of the Protocol with C, a lot of bit operations are performed. Because of the bit operation, the actual programming is not much, here is still a record.

The data from the C protocol is a 16 binary string.

The first is to convert the 16 binary string to Bytebuffer.

     Public Static bytebuffer String2buffer (String source) {        = bytebuffer.allocate (Source.length ()/2);          for (int idx = 0; idx < buffer.capacity (); idx++) {            int bytevalue = integer.parseint (sou Rce.substring (IDX * 2, IDX * 2 + 2), +);            Buffer.put ((byte) bytevalue);        }        Buffer.position (0);         return buffer;    }

The byte data is then taken from the Bytebuffer.

int flag=0; Bytebuffer buffer=nochelper.string2buffer (source);          while (Buffer.position () < buffer.limit ()) {            flag=buffer.get () & 0x0ff;        }

This is a circle, converting 16 characters into unsigned 10 digits.

Because each bit in each byte represents a different piece of information. Which takes a byte in the high 4-bit and low 4-bit time. Right SHIFT and A & operation are used.

By moving the 4-bit right, you can get a high 4-bit value.

The & operation with 0x0f, equivalent to 00001111 for the & operation, 0x0f equivalent to a mask, the height of four bits is set to 0, only the low four bits are reserved.

When judging the state of a bit in a byte, the previous practice is to use a mask. For xxxxx1xx This format data, verify that the low three bit of Foo is 1. When the value of the judgment is manipulated, the result of Foo & Integer.parseint ("00000100", 2) is judged, equal to 00000100 (4) is satisfied.

The current use of these, lest later to forget.

Java bit manipulation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.