将4个不同的整数转换为固定长度的字节数组 [英] Converting 4 different integers into a set length byte arrays

查看:34
本文介绍了将4个不同的整数转换为固定长度的字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从文本文件转换4个整数,并将其转换并分配为26个字节的字节数组.

I'm trying to convert 4 integers from a text file and convert and assign them into a byte array of 26 bytes.

例如文本文件包含数字 1 8 113 4 ,这四个整数将按此确切顺序连续放置:

Ex. Text file contains numbers 1 8 113 4 and these four integers are to be placed in this exact sequence consecutively:

001 01000 0001110001 00000100

为了进一步重申,我希望设置4个字节并将一个int放入其中,因此不要像这样输出2个

To further reiterate I want to have 4 bytes set and put an int into, so instead of outputting 2 like this

10

我想要它

0010

基本上对于上面的示例,我只想要4个不同的字节数组,它们的设置长度分别为3、5等,并希望将int插入每个数组中.抱歉,令人困惑.

Basically for the example above I just want 4 different byte arrays that have a set length of 3, 5, etc and want to insert an int into each array. Sorry for making it confusing.

推荐答案

如果我理解您的问题,您可以通过编写一个函数来开始,该函数用前导字符填充 String .像

If I understand your question, you could start by writing a function to pad a String with a leading character. Something like

public static String padString(String in, char padChar, int length) {
    StringBuilder sb = new StringBuilder(length);
    sb.append(in);
    for (int i = in.length(); i < length; i++) {
        sb.insert(0, padChar);
    }
    return sb.toString();
}

然后,您可以调用 Integer.toBinaryString(int) 并将结果传递给 padString

public static void main(String[] args) {
    System.out.println(padString(Integer.toBinaryString(2), '0', 4));
}

输出是(按要求)

0010

这篇关于将4个不同的整数转换为固定长度的字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆