【问题标题】:Convert string to hex将字符串转换为十六进制
【发布时间】:2014-12-25 03:10:20
【问题描述】:

我必须以动态方式更新时钟的日期和时间。我无法将字符串转换为变量 char(不是 char 数组)接受的格式。

还有其他方法吗?

这样就可以了!但不是那么有活力……

char year = 0x0E;
char month = 0x0A;
char day = 0x0A;
char hour = 0x0A;
char min = 0x0A;
char sec = 0x0A;

byte[] date_hour = new byte[]{(byte) 0xFE, (byte) 0x82, (byte) 0x71, (byte) 0x00, (byte) 0x0B, 
                   (byte) 0x01, (byte) 0x00, (byte) 0x07, 
                   (byte) year, (byte) month, (byte) day, (byte) hour, (byte) min, (byte) sec, 
                   (byte) 0x0A, (byte) 0x17, (byte) 0x0E, (byte) 0x0A, (byte) 0x17};

out.write(date_hour);

我想要类似的东西:

public String getYear() {
    return year;
}

//gets...

char year = getYear();
char month = getMont();
char day = getDay();
char hour = getHour();
char min = getMin();
char sec = getSec();

byte[] date_hour = new byte[]{(byte) 0xFE, (byte) 0x82, (byte) 0x71, (byte) 0x00, (byte) 0x0B, 
                   (byte) 0x01, (byte) 0x00, (byte) 0x07, 
                   (byte) year, (byte) month, (byte) day, (byte) hour, (byte) min, (byte) sec, 
                   (byte) 0x0A, (byte) 0x17, (byte) 0x0E, (byte) 0x0A, (byte) 0x17};

out.write(date_hour);

我试过了: Hex-encoded String to Byte Array How to convert/parse from String to char in java?

对不起我的英语不好... 谢谢!

【问题讨论】:

  • 您需要的 char 值与字符串中的字符没有关系。相反,它们是存储在char(只是一个小整数)中的数值。 (事实上​​,您可能根本不应该使用char,而应该将您的值声明为byte。)
  • 是的,小时值不是字符 - 从使用适当的数据类型开始。 Joda time 有一些不错的类,Java8 有一个不错的日期/时间包。
  • 我不明白这个问题......你真正想做什么? out.write 是什么?为什么会有字节数组?
  • 我做到了!谢谢int year = Integer.parseInt("0E",16);byte[] date_hour = new byte[]{(byte)((year)&0xff)};

标签: java string char hex byte


【解决方案1】:

如果要将String转换为char,可以这样做:

假设str是字符串的变量名。

char ch = str.toCharArray()[0];

或者,您可以使用:

char ch = str.charAt(0);

这两个都将存储字符串str的第一个字符(如果字符串是真正的字符,这将是唯一的字符)到字符ch中。

【讨论】:

    猜你喜欢
    • 2018-01-31
    • 2018-01-22
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2015-12-24
    相关资源
    最近更新 更多