PowerShell the method of converting IP address into binary _powershell

Source: Internet
Author: User

An IPv4 address is actually a 32-bit binary number, and then we divide it into four segments, each with 8 bits. The range that can be expressed in 8-bit binary is 0~255, so the value of each digit in dotted decimal notation is between 0~255. Sometimes, for example, in order to convert the subnet mask, we need to restore the IP address to the form of a binary string, such as: 11000000101010000000110000100001. Today I saw an example to complete this operation.

 code show as below:

$ipV4 = '192.168.12.33'
-join ($ipV4.Split('.') | ForEach-Object {[System.Convert]::ToString($_,2).PadLeft(8,'0')})
#-join is to combine multiple result objects or array elements together and output.

code show as below:
11000000101010000000110000100001
We can also modify the program to show the converted form of each paragraph:
 code show as below:
$ipV4.Split('.') | ForEach-Object {
   '{0,5}: {1}' -f $_, [System.Convert]::ToString($_,2).PadLeft(8,'0')
}

code show as below:
192: 11000000
 168: 10101000
  12: 00001100
  33: 00100001
 
Finally, let me explain the understanding of this sentence "[System.Convert]::ToString($_,2)". First, $_ represents the current loop variable. After splitting a dotted decimal IP using the Split method, each loop variable is a number, namely 192, 168, 12, and 33. And "[System.Convert]::ToString($_,2)" means to convert these numbers into binary strings. For a detailed understanding of [System.Convert]::ToString, you can parameterize the following examples:
code show as below:
#Binary
PS C:\Users\Editor> [System.Convert]::ToString(16,2);
10000
#Octal
PS C:\Users\Editor> [System.Convert]::ToString(16,8);
20
#Decimal
PS C:\Users\Editor> [System.Convert]::ToString(16,10);
16
#Hexadecimal
PS C:\Users\Editor> [System.Convert]::ToString(16,16);
10


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.