zoukankan      html  css  js  c++  java
  • 一次面试题,将 字符串 保存在 Byte 数组中

    最近在面试,遇到一个面试题

    字符串 String str = "AD428C93DE" 编程实现把 str 的内容放到 Byte[6] b 的数组中,存入后并能恢复原来的字符串。

    初始看到该题,有点一愣,感觉用 ascii 编码也无法保存这字符串啊。
    后来才明白一点,要把 ABCDE 字符当做 16 进制中的 ABCDE存储,刚好都是小于 5位就可以保存的,要是多个 F 就无法保存了。

    package com.util;
    
    /**
     * @Author: Robert_mml
     * @Version 1.0 2019/11/6
     */
    public class StringUtils {
    
        public static void main(String[] args) {
            String a = "AD428C93DE";
    
            byte[] bytes = new byte[6];
    
            StringBuilder sb = new StringBuilder();
    
            String[] split = a.split("");
            for (int i = 0; i < split.length; i++) {
                sb.append(split[i]);
                if (i % 2 != 0) {
                    int str2HexInt = str2HexInt(sb.toString());
                    bytes[i / 2] = (byte) str2HexInt;
                    sb.delete(0, 2);
                }
            }
    
            for(byte b : bytes) {
                if (b > 0) {
                    System.out.println(b);
                } else {
                    System.out.println(256 + b);
                }
            }
    
        }
    
        static final char[] chars = "0123456789ABCDEF".toCharArray();
        public static int str2HexInt(String str){
            char[] chars1 = str.toCharArray();
            int result = 0;
            for (int i = 0; i < chars1.length; i++) {
                for (int j = 0; j < chars.length; j++) {
                    if (chars1[i] == chars[j]) {
                        result = (result << 4) | j;    // 相当于 将 原数据 * 16 再加上 新数据, 16进制计算成10进制
                    }
                }
            }
            return result;
        }
    
    }

    通过记录字符位置,进行保存, 可以将 ABCDEF 字符转成 16 进制的数字,

    然后将两个字符存在一个 Byte 里, 根本就用不到 6 位数组, 5 位就可以搞定。

  • 相关阅读:
    pat00-自测5. Shuffling Machine (20)
    Spiral Matrix
    Search in Rotated Sorted Array II
    Search in Rotated Sorted Array
    Best Time to Buy and Sell Stock II
    4Sum
    3Sum Closest
    3Sum
    MySQL存储过程、函数和游标
    Word Ladder
  • 原文地址:https://www.cnblogs.com/mmling/p/11806057.html
Copyright © 2011-2022 走看看