2017年9月23日 星期六

[Python] 檢查台灣身份證號碼

最近學習 python,實作書本上的題目,其中一個練習是檢查所輸入的身份正證號碼是否正
確。

台灣身份證的編碼規則,請參考該網址說明。

實作概念:
1. 透過 Dictionary 建立身分證第一碼(地區碼)的對應表:對應表內容皆由 List 產生,透過 zip() 將英文和數字編碼合併在一起,而建立出地區碼對應表
2. 偵測明顯的錯誤(如:長度錯誤,第一碼非英文字元...等)
3. 將輸入的身份證內容取出,並根據身份證編碼規則,將輸入內容轉換成 check sum
4. 檢查 check sum 是否符合身分證編碼規則

程式碼:

import string

# create alphabet for 1st char of ID
alphabet = list(string.ascii_uppercase[0:8])
alphabet.extend(list(string.ascii_uppercase[9:]))
code = list(range(10,33))

# create the location mapping code for char of ID
locationCode = dict(zip(alphabet,code))

while(1):
    id = input('Please input your security id: ')
    if id == 'exit':
        break
    elif len(id) != 10 or not(id[0].isalpha()) \
            or not(id[1:].isdigit() or int[id[1] > 2 or id[1] < 1]):
        print('Error: wrong format')
        continue
    # Convert 1st Alphabet to Numeric code
    encodeID = list(str(locationCode[id[0].upper()]))
    encodeID.extend(list(id[1:]))
    print(encodeID)
    checkSum = int(encodeID[0])

    # Calculate the checksum of ID
    para = 9
    for n in encodeID[1:]:
        if para == 0:
            para = 1
        print(n, para)
        checkSum += int(n)*para
        para -= 1

    # Check the checksum
    if checkSum % 10 == 0:
        print("ID is correct")
    else:
        print('Error: ID is not correct')

2016年5月31日 星期二

Get MAC address using C program

static int getmac() {
    struct ifreq ifr;
    struct ifconf ifc;
    char buf[1024];
    int success = 0;

    int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    if (sock == -1) {
        // handle error 
    }

    ifc.ifc_len = sizeof(buf);
    ifc.ifc_buf = buf;

    if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) {
        // handle error
    }

    struct ifreq* it = ifc.ifc_req;
    const struct ifreq* const end = it + (ifc.ifc_len / sizeof(struct ifreq));

    for (; it != end; ++it) {
        strcpy(ifr.ifr_name, it->ifr_name);
        if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
            if (! (ifr.ifr_flags & IFF_LOOPBACK)) { // don't count loopback
                if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
                    success = 1;
                    break;
                }
            }
        }
        else {
            // handle error 
        }
    }
    close(sock);

    unsigned char mac[6];

    if (success) memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
    printf("Get Mac from asLicense : %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\n" , mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
}

2015年1月14日 星期三

Get Java Package Name from C via JNI

MainActivity.java

package com.example.test;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

    //Load Jni library
    static {
  System.loadLibrary("JniLibrary");
    }
    //Declare Jni method
    public native int callPknName(Context context);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Log.i("Tag", "length of package name: " + callPknName(this));
    }    
}

---------------------------------------------------------------------------------------------------------------

JniLibrary.c

#include <jni.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>


JNIEXPORT jint JNICALL Java_com_example_test_pkg_callPknName (JNIEnv *env, jobject obj, jobject activity) {

//Get java context class
jclass java_class = (*env)->GetObjectClass(env, activity);

//Check if get class
if (java_class == 0) {
return 0; // did not get class
}

//Get method "java Context.getPackageName()"
 //"()Ljava/lang/String;" means this method has no input argument, and returns "String" type
jmethodID java_method = (*env)->GetMethodID(env, java_class, "getPackageName", "()Ljava/lang/String;");

//Check if get method
if (java_method == 0) {
return 0; //did not get method
}

//Convert java string object to jstring
jstring java_string = (*env)->CallObjectMethod(env, activity, java_method);

//Check if get java string value
if (java_string == 0) {
return 0; //did not get method
}
//Conver jstring to char*
const char *inputLic = (*env)->GetStringUTFChars(env, java_string, NULL);
     return strlen(inputLic);
}


---------------------------------------------------------------------------------------------------------------

Reference: 
6.1  Callback the Constructor to Create a New Java Object in the Native Code:

Stack Overflow: