将输入字符串转换为十六进制数字表示

时间:2012-02-29 06:19:59

标签: java c java-native-interface hex

我在java代码中使用类似“abcd”的字符串作为命令行参数。我需要将此字符串传递给我的C JNI代码,该代码应该使用此字符串并将其用作共享内存标识。 我想知道如何以及在哪里使这个字符串代表一个hexa值。

4 个答案:

答案 0 :(得分:0)

你有没有尝试过类似的东西:

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

如果您正在寻找,那么您可以查看printf方法,它基于Formatter

答案 1 :(得分:0)

您只需要:

Integer.parseInt("abcd", 16);

答案 2 :(得分: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时有几个方面。

答案 3 :(得分: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));
}
}