简体   繁体   English

在Java中,我将如何获取输入的IP地址并将其转换为特定位

[英]In Java, how would I take an inputed IP address and convert it into its specific bits

Basically what I am needing is a way to take the input from the user of their ip address, then output the subsequent 8bits for each section as to which bits are on and off. 基本上,我需要的是一种从用户的IP地址获取输入,然后为每个部分输出随后的8位(打开和关闭)的方法。

I currently have the user inputting their ip address in each section like so: 我目前让用户在每个部分中输入其IP地址,如下所示:

System.out.print("Please input the first set in your IP Address: ");
strHolder = kb.next();
first = Integer.parseInt(strHolder);

System.out.print("Please input the second set in your IP Address: ");
strHolder = kb.next();
second = Integer.parseInt(strHolder);

System.out.print("Please input the third set in your IP Address: ");
strHolder = kb.next();
third = Integer.parseInt(strHolder);

System.out.print("Please input the fourth set in your IP Address: ");
strHolder = kb.next();
fourth = Integer.parseInt(strHolder);

I'm not very experienced at Java. 我对Java不太有经验。 I've taken one class in college, and most of this I had to google how to do, but I've found nothing in regards to the bit process. 我在大学上过一堂课,大部分时间我都必须用谷歌搜索该怎么做,但是我却没有发现关于位过程的任何信息。

String s = Integer.toBinaryString(first);

If the input will be like: 123.124.125.126 (one string), you can make String[] strListHolder = strHolder.split(".") and operate on that. 如果输入如下所示: 123.124.125.126 (一个字符串),则可以使String [] strListHolder = strHolder.split(“。”)并对其进行操作。

Integer[] holder = new Integer[strListHolder.count];
for(int i = 0; i < strListHolder.count; i++){
    holder[i] = Integer.parseInt(strListHolder[i]);
}

Is that what you wanted? 那是你想要的吗? @EDIT After that you can check n'th bit of each partusing: @EDIT之后,您可以使用以下命令检查每个零件的第n位:

if ((holder[i] & (1 << n)) != 0)
{
   // The bit was set
}

The IP address(IPV4) is of the format xxx.xxx.xxx.xxx . IP地址(IPV4)格式为xxx.xxx.xxx.xxx

Suppose the input is a string format. 假设输入是字符串格式。 1st seprate the 4 parts using split function in the string class. 1使用字符串类中的split函数分隔这4个部分。 The you can take the individual parts and & them with 255 to get the bits which are set and use the same information to find the bits which are not set. 您可以将单个零件和&用255进行取值,以获取已设置的位,并使用相同的信息来查找未设置的位。

String[] str = ip.split(".");
for (String each : str) {
    System.out.println(Integer.parseInt(each) & 255);  // this would print the set bits just convert it to binary
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM