Android编程学习笔记之ip2id程序,公司一个项目中需要给一系列网络设备分配id号,id是根据ip算出来的,算法如下:
id共3个字节,高字节:从机号:1-31;后两个字节为ip号的最后两个字节.如ip为192.168.0.240的一台设备从机号为31.则id号为31,00,240换算成十进制为2031856.
源码:
package com.id2ip; import android.app.Activity; import android.os.Bundle; import android.widget.*; import android.view.*; public class id2ip extends Activity { /** Called when the activity is first created. */ private TextView text; private Button button; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //获得文本框ID text = (TextView)findViewById(R.id.editText1); //获得按钮ID button = (Button)findViewById(R.id.button1); //重载按键监听方法 button.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { //获得输入框文本 CharSequence str = text.getText(); do { //判断输入是否有效 //如果输入位数不为8位,则无效 if (str.length() != 8) { text.setText("输入位数必须为8位"); break; } //输入的字符不为数字,则无效 int i = 0; for (i = 0;i < 8;i++) { if ((str.charAt(i) < '0') || (str.charAt(i) > '9')) { break; } } if (i < 8) { text.setText("输入字符必须为数字"); break; } String str_temp = str.toString(); //转换为数字 long num = Long.parseLong(str_temp); //ip2id short slave_num = (short)(num / 1000000); num = num % 1000000; short ip1 = (short)(num / 1000); num = num % 1000; short ip0 = (short)num; long num_temp = ip0; num_temp |= ip1 << 8; num_temp |= slave_num << 16; str_temp = Long.toString(num_temp); str = str_temp; text.setText(str); }while (false); } }); } }注意:
程序中需要注意的地方有3处:
一是字符串转数字,可以用方法Long.parseLong();
二是在android中常用的捕捉空间字符串的类是CharSequence,而java中常用的字符串类为String,则需要转换.
1.CharSequence转String
CharSequence str;
String str_temp = str.toString();
2.String转CharSequence这个直接等于就可以了:str = str_temp;