Java Binary conversion (ignoring positive and negative differences)

Source: Internet
Author: User

Recently looked at the study materials, the sense of conversion is actually very interesting, especially for negative this aspect.

Below to share with you, here only write decimal to binary conversion, in fact, are the same truth

1  Public classTest1 {2 3      Public Static voidMain (string[] args) {4ToBin (-4);5ToBin (4);6     }7     /*8 * Function Name: ToBin9 * Function Description: Used to convert positive or negative numbers into binary numbersTen * Person created: ZX One * return value: void A      * */ -      Public Static voidToBin (intnum) { -         //defines a string that is used to store the computed binary data theStringBuffer sb=NewStringBuffer (); -          while(num!=0){ -             //to add a computed binary number to a string -             //Note: The use of & operations here, do not understand the reader, you can find on the Internet +Sb.append (num&1); -             //unsigned bit operations on NUM, similar to the 2 operation, require the reader to find the exact difference +Num=num >>> 1; A         } at         //outputs the string in reverse order, - System.out.println (Sb.reverse ()); -     } -  -}
View Code

If you want to write a 8-binary conversion, you can change the two statements in the while loop to:

Sb.append (num&7); Num=num >>> 3;

If you want to write a 16-binary conversion, you can change the two statements in the while loop to:

Sb.append (num&15); Num=num >>> 4;

Java Binary conversion (ignoring positive and negative differences)

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.