将int转换为字节数组,并使用System.out.write方法打印到控制台。

19 浏览
0 Comments

将int转换为字节数组,并使用System.out.write方法打印到控制台。

我有这个程序:\n

public class Duplicates {
    public static void main(String[] args) {
        byte[] bytes = "hz".getBytes();
        for (int i = 0; i < 10_000_000; i++) {
            System.out.write(bytes, 0, bytes.length);
        }
    }
}

\n开始后,输出如下:\nhzhzhzhzhzhzhzhz.....hz\n\n但是如果我尝试将`int`转换为字节数组并打印:\n

public class Duplicates {
    public static void main(String[] args) {
        byte[] bytes = ByteBuffer.allocate(4).putInt(666).array();
        for (int i = 0; i < 10_000_000; i++) {
            System.out.write(bytes, 0, bytes.length);
        }
    }
}

\n开始后,输出如下:\n

�  �  �  �  �  �  �  �  �  �  �  �  �  �  �  �  �  �
  �  �  �  �  �  �  �  �  �  �  �  �  �

\n我想在控制台的每一行上打印`666` 10,000,000次,并且不超过20MB的内存或1秒的时间。我做错了什么?\n编辑 如果我使用@Justin的例子`Integer.toString(i).getBytes()`,我得到了这个结果:\n[图片链接](https://i.stack.imgur.com/ZfgVS.png)

0
0 Comments

问题的出现原因是在代码中将整数转换为字节数组并打印到控制台时出现了错误。解决方法是将整数转换为字符串后再进行转换和打印。

具体的解决方法如下:

1. 将整数转换为字符串:使用Integer.toString()方法将整数转换为字符串。

String str = Integer.toString(input);

2. 将字符串转换为字节数组:使用String.getBytes()方法将字符串转换为字节数组。

byte[] bytes = str.getBytes();

3. 打印字节数组到控制台:使用System.out.write()方法将字节数组打印到控制台。

System.out.write(bytes);

以上是解决问题的步骤,通过将整数转换为字符串,再将字符串转换为字节数组,最后打印字节数组到控制台,可以实现将整数转换为字节数组并打印到控制台的功能。如果需要在循环中打印多个整数的字节数组,可以将以上步骤放在循环中执行。

希望以上内容对您有所帮助。如果还有其他问题,请随时提问。

0
0 Comments

问题的原因是调用System.out.write()方法存在一些开销。解决方法是使用一个较大的缓冲区,将输入值的一些重复填充到缓冲区中。以下是解决方法的代码示例:

long start = System.currentTimeMillis();
byte[] bytes = String.valueOf(666).getBytes();
// 使用20MB的内存作为输出缓冲区
int size = 20 * 1000 * 1000 / bytes.length;
byte[] outBuffer = new byte[size * bytes.length];
// 填充用于System.out.write()的缓冲区
for (int i = 0; i < size; i++) {
    System.arraycopy(bytes, 0, outBuffer, i * bytes.length, bytes.length);
}
// 使用较大的缓冲区进行实际写入
int times = 10_000_000 / size;
for (int i = 0; i < times; i++) {
    System.out.write(outBuffer, 0, outBuffer.length);
}
long end = System.currentTimeMillis();
System.out.println();
System.out.println("Took " + (end - start) + "Millis");

以上代码将666输出一千万次,耗时约为600毫秒。

0