C#轉java須要注意的問題

開發場景:java

把圈存機的程序移植到安卓環境(A302多媒體pos機)算法

 

----------------------------數組

傳引用函數

C# 有ref out的方法傳引用。加密

java默認是不支持傳引用的,若是必定要傳,能夠用聲明對象的方式,傳一個對象,而後在函數內部處理對象跟傳引用是相似的。spa

另外還有一種方式是傳byte[] byte數組默認是引用的效果。對象

 

例:ip

 

傳對象ci

ClassA a = new ClassA();開發

a.id = 1;

test(a);

String test_a = a.id ; // test_a 爲 2

 

 

function test(ClassA a){

a.id = 2;

}

 

 

傳byte[]

 

byte[] t = new byte[1];

t[0] = 1;

test(t); // 執行完後 t[0] 爲 2

 

 

function test(byte[] a){

a[0] = 2;

}

 

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

byte類型的範圍不一樣

C#是 0 至 255

java 是 -128 至 127

默認狀況下是能夠直接轉換的。

若是在java上寫255,能夠這樣 (byte)255。

 

有一種狀況須要注意 在位運算(如操做符 <= >= << >>)等操做時,結果會不同。

通常像這種狀況,都是遇到最基礎的函數問題,建議在網上搜集一下相關的java版的函數。

 

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

Zlib壓縮

C#上採用的byte[]數組壓縮轉換爲java版的以下,別的壓縮後結果不同(這個問題當時花了兩天時間)

 

/**

 * 壓縮

 * 

 * @param data

 *            待壓縮數據

 * @return byte[] 壓縮後的數據

 */

public static byte[] compress(byte[] data) {

byte[] output = new byte[0];

 

Deflater compresser = new Deflater();

 

compresser.reset();

compresser.setInput(data);

compresser.finish();

ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);

try {

byte[] buf = new byte[1024];

while (!compresser.finished()) {

int i = compresser.deflate(buf);

bos.write(buf, 0, i);

}

output = bos.toByteArray();

} catch (Exception e) {

output = data;

e.printStackTrace();

} finally {

try {

bos.close();

} catch (IOException e) {

e.printStackTrace();

}

}

compresser.end();

return output;

}

 

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

返回首頁的跳轉

 

Intent intent = new Intent(mContext, MainActivity.class);

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

startActivity(intent);

 

跳回首頁最好加這兩個參數,能夠保證界面返回不會重複。

 

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

DES加密算法

java版的以下。網上有不少不正確的版本。

 

/**

 * des加密算法,ECB方式,NoPadding模式,數據字節必須是8的整數倍

 * 

 * @param key

 * @param data

 *            數據字節必須是8的整數倍

 * @return

 * @throws Exception

 */

public static byte[] encryptECBPKCS5Padding(byte[] key, byte[] data) throws Exception {

 

Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

DESKeySpec desKeySpec = new DESKeySpec(key);

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

 

cipher.init(Cipher.ENCRYPT_MODE, secretKey);

 

return cipher.doFinal(data);

 

}

相關文章
相關標籤/搜索