java - Convert Strings of 0 & 1 into bytes -
i have 2 strings:
string = "11111"; string b = "10001";
i'd make bitwise comparison wih "&"
operator.
what best way ?
- first, convert each binary
string
long
valuelong.parselong(s, 2)
. method parse given string using radix of 2, meaning should interpret string binary. - calculate bitwise comparison
&
on 2long
values. - convert binary string
long.tobinarystring(i)
.
here's sample code:
public static void main(string[] args) { string = "11111"; string b = "10001"; long la = long.parselong(a, 2); long lb = long.parselong(b, 2); long lc = la & lb; string c = long.tobinarystring(lc); system.out.println(c); // prints 10001 }
another way without using primitive long
value manually looping on digits , storing &
result of code points in stringbuilder
:
public static void main(string[] args) { string = "11111"; string b = "10001"; stringbuilder sb = new stringbuilder(a.length()); (int = 0; < a.length(); i++) { sb.appendcodepoint(a.codepointat(i) & b.codepointat(i)); } string c = sb.tostring(); system.out.println(c); }
Comments
Post a Comment