The reciprocal conversion of byte and bit in the seventh week of Operation--java

Source: Internet
Author: User

This week the information security class did the DES encryption algorithm experiment, needs to the bit operation. Here's a summary:

1 byte = 8 bit

There is no bit data type in Java, so you can have a numeric value (1,0) for each bit in the byte[] array.

To extract each one, you need to move it to the right first, in and 1 (2 binary for 000000001) and the operation, so in addition to the required bit, the other is 0. Its 2 binary (1,0), exactly the number 1, 0;

The specific code is as follows:

     Public Static byte [] Bytetobit (byte  a) {          bytenewbyte[8];            for (int i = 7; I >= 0; i--) {              = (byte) ((a >> i) & 1);          }         return  temp;      

The following is the conversion of an array of byte[] with a bit value into a byte whose thought is exactly the opposite of the above;

The specific code is as follows:

public static byte Bittobyte (byte[] a) {byte temp = (byte) 0;for (int i = 0; i < bits; i++) {temp = temp | a[i] << ; i;} return temp;}

  

The reciprocal conversion of byte and bit in the seventh week of Operation--java

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.