将一个位转换为Base64字符

huangapple go评论90阅读模式
英文:

Convert a bit to Base64 character

问题

我需要将一个二进制字符串("110100",十进制为52)转换为对应的Base64字符,我知道对应的字符是"0"。在Java中有没有这样的方法?我阅读了多个Base64指南,但是我找不到答案。

为了澄清起见,转换表在这里:https://www.lifewire.com/base64-encoding-overview-1166412(Base64编码表部分)。我想要在已知52的情况下,将其转换为"0"字符。

非常感谢。

英文:

I need to convert a binary String ("110100", 52 in decimal) to its corresponding Base64 character, that I know is "0". Is any way in Java to do that? I was reading multiple base 64 guides but I cant reach the answer.

For clarification, the conversion table is here: https://www.lifewire.com/base64-encoding-overview-1166412 (Base64 Encoding Table section) I want having the 52, convert it to "0" char.

Thanks a lot.

答案1

得分: 1

由于一个字节长度为8位,而Base64通过仅使用6位来构造其值,我能想到的最简单的方法是在所需字符开头附加两个字符,然后仅取结果的最后一个字符:

String encode = String.format("00%s", (char) Integer.parseInt("110100", 2));
String encoded = new String(Base64.getEncoder().encode(encode.getBytes()));
System.out.println(encoded.charAt(encoded.length() - 1));
// 输出:0
英文:

Since a byte is 8 bits long and Base64 makes up its values by grabbing only 6 bits the simplest way I can think of is appending two characters at the beginning of your desired character and taking only the last character of the result:

String encode = String.format("00%s", (char) Integer.parseInt("110100", 2));
String encoded = new String(Base64.getEncoder().encode(encode.getBytes()));
System.out.println(encoded.charAt(encoded.length() - 1));
// Prints: 0

答案2

得分: 0

你首先需要将二进制字符串转换为字节数组。有很多关于如何完成这个操作的帖子,但在伪代码中,它看起来像是这样的。

  读取最多4个字符;

  Byte.parseByte(chars, 2);

  添加到字节数组;

然后你可以使用 Base64.Encoder 来对字节进行编码。

英文:

You first need to convert your binary string into a byte array. There are a number of posts on how to accomplish this but in pseudo code it would look like the following.

  Read up to 4 characters;

  Byte.parseByte(chars, 2);

  Append to byte array;

Then you can use Base64.Encoder to encode the bytes.

huangapple
  • 本文由 发表于 2020年9月11日 05:09:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63837732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定