将字符串转换为二进制[考试] [英] Converting a string to binary [Java]

查看:186
本文介绍了将字符串转换为二进制[考试]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有以下字符串:

Let's say I have the following string:

String s = "Hello, stackoverflow"

我将如何将其转换成二进制数(0和1)?这里的窍门:我不允许使​​用内置方法的转换。它必须在数学上进行。我不知道从哪里开始。任何人都可以点我在正确的方向?

How would I convert that into a binary number (0s and 1s)? Here's the trick: I'm not allowed to use built-in methods for the conversion. It has to be done mathematically. I have no idea where to begin. Can anyone point me in the right direction?

编辑1:我已经看到了这个的问题和人民使用的getBytes(串)建议,字符集UTF-8和Integer.toBinaryString。我不能使用任何这些方法进行转换。我还没有听说过36基无论是。

Edit 1: I've seen this question and people suggested using getBytes(string), charset UTF-8, and Integer.toBinaryString. I'm not allowed to use any of these methods for conversion. I haven't heard of 36-base either.

推荐答案

首先获得使用 getByte()在函数然后使用整数字节格式字符串。 toBinaryString(字节)功能。 &安培;完蛋了。

First get bytes form string using getByte() function then use Integer.toBinaryString(byte) function. & thats it.

请注意:〜确保 Integer.toBinaryString(字节)接受INT(或在这种情况下,字节不是全部。)所以你必须按字节通过字节(可能。为循环。)

NOTE:~ Make sure Integer.toBinaryString(byte) accepts int(or in this case byte not all.) so you have to pass byte by byte.(may be for loop.)

编辑:〜
你可以做的是焦炭和放大器解析字符串字符;每个烧焦您可以用得到的ASCII值。

Edited :~ what you can do is parse string char by char & for each char you can get ascii value using.

int tempChar = (int)ch;

然后simpley使用。

Then simpley use this.

Integer.toString(tempChar,2);

试试这个。

string finalString = "";
for(int i = 0;i<myStr.length;i++){
    int tempChar = (int)ch;
    finalString = finalString + Integer.toString(tempChar,2);//& this is not allowed then now only you need to create function for integer to binary conversion.
}
System.out.println("Your byte String is"+finalString);

这篇关于将字符串转换为二进制[考试]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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