[英]converting the input string as a hexa number representation
I take a string like "abcd" as a command line argument in my java code. 我在Java代码中将字符串“ abcd”作为命令行参数。 I need to pass this string to my C JNI code which should take this string and use it as a shared memory identity.
我需要将此字符串传递给我的C JNI代码,该代码应采用此字符串并将其用作共享内存标识。 I am looking to know how and where I can make this string to be representing a hexa value.
我想知道如何以及在哪里可以使此字符串表示一个六进制值。
所有你需要的是:
Integer.parseInt("abcd", 16);
Java or C? Java还是C? In C, you use
strtoul
: 在C中,您使用
strtoul
:
#include <stdlib.h>
int main(int argc, char * argv[])
{
if (argc > 1)
{
unsigned int n = strtoul(argv[1], NULL, 16);
}
}
Check the manual; 检查手册; when parsing user input it's vital to check for errors, and there are several aspects to this when using
strtoul
. 解析用户输入时,检查错误至关重要,而使用
strtoul
时有很多方面。
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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.