2012-02-29 146 views
1

我在我的java代碼中使用了一個字符串「abcd」作爲命令行參數。我需要將此字符串傳遞給我的C JNI代碼,該代碼應該接受此字符串並將其用作共享內存標識。 我期待知道如何以及在哪裏我可以使這個字符串代表一個六進制值。將輸入字符串轉換爲六位數表示形式

回答

0

Java或C?在C中,您使用strtoul

#include <stdlib.h> 

int main(int argc, char * argv[]) 
{ 
    if (argc > 1) 
    { 
     unsigned int n = strtoul(argv[1], NULL, 16); 
    } 
} 

檢查手冊;在解析用戶輸入時,檢查錯誤至關重要,並且在使用strtoul時有幾個方面。

0

您是否嘗試過這樣的事情:

final String myTest = "abcdef"; 
for (final char c : myTest.toCharArray()) { 
    System.out.printf("%h\n", c); 
} 

如果這是你在找什麼,你可以看看printf的方法,它是基於Formatter

0

所有你需要的是:

Integer.parseInt("abcd", 16); 
0
public class HexString { 
    public static String stringToHex(String base) 
    { 
    StringBuffer buffer = new StringBuffer(); 
    int intValue; 
    for(int x = 0; x < base.length(); x++) 
     { 
     int cursor = 0; 
     intValue = base.charAt(x); 
     String binaryChar = new String(Integer.toBinaryString(base.charAt(x))); 
     for(int i = 0; i < binaryChar.length(); i++) 
      { 
      if(binaryChar.charAt(i) == '1') 
       { 
       cursor += 1; 
      } 
     } 
     if((cursor % 2) > 0) 
      { 
      intValue += 128; 
     } 
     buffer.append(Integer.toHexString(intValue) + " "); 
    } 
    return buffer.toString(); 
} 

public static void main(String[] args) 
    { 
    String s = "abcd"; 
    System.out.println(s); 
    System.out.println(HexString.stringToHex(s)); 
} 
} 
相關問題