【问题标题】:converting the input string as a hexa number representation将输入字符串转换为十六进制数字表示
【发布时间】:2012-03-18 15:54:27
【问题描述】:

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

【问题讨论】:

    标签: java c java-native-interface hex


    【解决方案1】:
    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));
    }
    }
    

    【讨论】:

      【解决方案2】:

      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】:

        你只需要:

        Integer.parseInt("abcd", 16);
        

        【讨论】:

          【解决方案4】:

          你有没有尝试过这样的事情:

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

          如果这是你要找的,你可以看看 printf 方法,它基于Formatter

          【讨论】:

            猜你喜欢
            • 2018-01-31
            • 1970-01-01
            • 1970-01-01
            • 2018-12-12
            • 2017-05-16
            • 2014-03-19
            • 2013-02-07
            相关资源
            最近更新 更多