2012-02-29 16 views
1

私はJavaコードのコマンドライン引数として "abcd"のような文字列を取る。この文字列をCのJNIコードに渡す必要があります。このコードは、この文字列を共有メモリIDとして使用する必要があります。 私はこの文字列をどのようにしてどこでヘキサ値を表すことができるのかを知りたいと思っています。入力文字列をヘキサ数字表現として変換する

答えて

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)); 
} 
} 
関連する問題