wallyone 2015-05-18 14:08 采纳率: 25%
浏览 3794
已采纳

如何将string转换为byte

开发中需要这样的功能,将String str = "0f8adffb11dc" 转换为byte[] byteText = { 0x0f, 0x8a, 0xdf, 0xfb,0x11, 0xdc};请问如何实现,谢谢!

  • 写回答

4条回答 默认 最新

  • danielinbiti 2015-05-18 14:49
    关注
     public class Test {
        public static byte uniteBytes(byte src0, byte src1) { 
            byte _b0 = Byte.decode("0x" + new String(new byte[]{src0})).byteValue(); 
            _b0 = (byte)(_b0 << 4); 
            byte _b1 = Byte.decode("0x" + new String(new byte[]{src1})).byteValue(); 
            byte ret = (byte)(_b0 ^ _b1); 
            return ret; 
        } 
        public static byte[] HexString2Bytes(String src){ 
            byte[] ret = new byte[src.length()/2]; 
            byte[] tmp = src.getBytes(); 
            for(int i=0; i<src.length()/2; i++){ 
                ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]); 
            } 
            return ret; 
        } 
        public static void main(String[] args) {
            byte[] byteText = { 0x0f, (byte) 0x8a, (byte) 0xdf, (byte) 0xfb,0x11, (byte) 0xdc};
            byte[] ret = Test.HexString2Bytes("0f8adffb11dc");
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样