本文目錄一覽:
怎樣表示二進位
如果與JAVA相同:
主要成員方法:
public static String toHexString(long i);將i轉換為16進位字元串
public static String toOctalString(long i);將i轉換為8進位字元串
public static String toBinaryString(long i);將i轉換為2進位字元串
toHexString
修改了一處
msg += “\\u” +Integer.toHexString((int)chars[i]);後面加入了” “
msg += “\\u” + Integer.toHexString((int) chars[i]) + ” “;目的是為了方便字元串的劃分(用\\u劃分字元串貌似不行)如果對這部有異議,可以選擇其它劃分字元串的方法.
添加了一個方法hexToString,用來將規定格式的句子還原為最初的字元串..按樓主題目的要求就是為了將十六進位數還原為”中華人民共和國”
public class strings {
static String msg = “”;
public static void main(String[] args) {
msg = tohex();
System.err.println(msg);
String result = hextoString(msg);
System.err.println(result);
}
public static String tohex() {
String test = “中華人民共和國”;
char[] chars = test.toCharArray();
for (int i = 0; i chars.length; i++) {
// 為了方便字元串劃分,在每個十六進位數結尾加上了空格
msg += “\\u” + Integer.toHexString((int) chars[i]) + ” “;
}
return msg;
}
public static String hextoString(String msg) {
// 下面三句是利用正則表達式,用空格作為分隔符
// 獲得每個”\\u”+十六進位數子串,並保存與strs數組
Pattern pattern;
pattern = Pattern.compile(” “);
String[] strs = pattern.split(msg);
char[] foreString = new char[strs.length];
String hexNum;
for (int i = 0; i strs.length; i++) {
hexNum = strs[i].substring(2);// 獲得”\\u”後面的十六進位數
int value = Integer.parseInt(hexNum, 16);// 將其轉化為十進位數
foreString[i] = (char) value;
}
return new String(foreString);
}
}
用C語言寫個程序:先獲取本機MAC地址,據此得到Link Local地址(IPv6 Address)
麻煩,不愛動手,上網查一下,就那麼兩個api,一用就ok了。easy的很。
#include winsock2.h
#include Iphlpapi.h
#include stdio.h
void byte2Hex(unsigned char bData,unsigned char hex[])
{
int high=bData/16,low =bData %16;
hex[0] = (high 10)?(‘0’+high):(‘A’+high-10);
hex[1] = (low 10)?(‘0’+low):(‘A’+low-10);
}
int getLocalMac(unsigned char *mac) //獲取本機MAC地址
{
ULONG ulSize=0;
PIP_ADAPTER_INFO pInfo=NULL;
int temp=0;
temp = GetAdaptersInfo(pInfo,ulSize);//第一次調用,獲取緩衝區大小
pInfo=(PIP_ADAPTER_INFO)malloc(ulSize);
temp = GetAdaptersInfo(pInfo,ulSize);
int iCount=0;
while(pInfo)//遍歷每一張網卡
{
// pInfo-Address 是MAC地址
for(int i=0;i(int)pInfo-AddressLength;i++)
{
byte2Hex(pInfo-Address[i],mac[iCount]);
iCount+=2;
if(i(int)pInfo-AddressLength-1)
{
mac[iCount++] = ‘:’;
}else
{
mac[iCount++] = ‘#’;
}
}
pInfo = pInfo-Next;
}
if(iCount 0)
{
mac[–iCount]=’\0′;
return iCount;
}
else return -1;
}
int main(int argc, char* argv[])
{
unsigned char address[1024];
if(getLocalMac(address)0)
{
printf(“mac-%s\n”,address);
}else
{
printf(“invoke getMAC error!\n”);
}
return 0;
}
需要這兩個:iphlpapi.lib , ws2_32.lib 靜態庫(VC添加到工程LINK里)
原創文章,作者:BBWVN,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/325050.html