查看: 565|回复: 3
|
来回转换二进制字符串(C#)
[复制链接]
|
|
本帖最后由 褐眼睛 于 10-3-2021 01:26 AM 编辑
下列C#源码展示如何转换二进制字符串(binary string)去二进制数(binary number),然后在转换回二进制字符串(binary string)。
当然它可以更改去16位或64位整数(integer).
- string binaryString = "011100100111001001110011";
- int G = 0;
- for (int i = 0; i < binaryString.Length; i++)
- G += (int)((binaryString[binaryString.Length - (i + 1)] & 1) << (i % 32));
- Console.WriteLine(G); //‭7500403‬
- binaryString = string.Empty;
-
- for (int i = 31; i >= 0; i--)
- binaryString += (char)((((uint)G & (1 << (i % 32))) >> (i % 32)) | 48);
- Console.WriteLine(binaryString); //00000000011100100111001001110011
复制代码
以下是计算二进制数里有多少个1......其实CPU指令也有POPCNT,
POPCNT — Return the Count of Number of Bits Set to 1
不过这是C#,所以无法直接使用CPU指令。
- uint G = 8501; //10 0001 0011 0101
- uint g = 0;
- for (int i = 0; i < 32; i++)
- {
- g += (G << (31 - (i % 32))) >> 31;
- }
- Console.WriteLine(g); //6
复制代码
大家有没有长见识?或者你有其他更好的方法吗? |
|
|
|
|
|
|
|
发表于 11-3-2021 02:16 PM
|
显示全部楼层
本帖最后由 flashang 于 11-3-2021 02:17 PM 编辑
試試看 (gcc):
- void popcnt() {
- unsigned long G = 8501; //10 0001 0011 0101
- unsigned long bits = 0;
- while( G > 0 ) {
- // bits = bits + (G & 1);
- // G = G >> 1;
- bits += (G & 1);
- G >>= 1;
- }
- printf( "while %d \n", bits );
- }
复制代码
|
|
|
|
|
|
|
|
楼主 |
发表于 12-3-2021 11:18 PM
|
显示全部楼层
|
|
|
|
|
|
|
楼主 |
发表于 12-3-2021 11:19 PM
|
显示全部楼层
让我放大招,如何转换十分(无限长)的二进制字符串?
- using System;
- public class GGG
- {
- public static void Main()
- {
- string testCase = "0001001000000010000000000010000111000011000101100000001100000000000010010100110100100011001001000101010010001100011100110000110010000001011000100101010001100001001000010100100100000000100001010000011100000001111111111111110101000000000111110111000100000110";
- //Console.Write("Please enter a binary string ('0' or '1' only): ");
- //string testCase = Console.ReadLine();
- uint[] G = new uint[(testCase.Length / 32) + 1];
- uint g = 0;
- for (int i = 0; i < testCase.Length; i++)
- {
- G[(i / 32)] += (uint)((testCase[testCase.Length - (i + 1)] & 1) << (i % 32));
- }
- for (int i = 0; i < testCase.Length; i++)
- {
- g += (G[(i / 32)] << (31 - (i % 32))) >> 31;
- }
- Console.WriteLine("There are " + g.ToString() + " occurrence(s) of '1'");
- Console.WriteLine("Below are the binary numbers stored in multiple 32-bit integer starting from leftmost bit:");
- for (int i = 0; i < (testCase.Length / 32) + 1; i++)
- {
- Console.WriteLine(G[i]);
- }
- Console.ReadLine();
- }
- }
复制代码
运行结果:
There are 88 occurrence(s) of '1'
Below are the binary numbers stored in multiple 32-bit integer starting from leftmost bit:
1075802374
117571581
558432389
2170704993
1418490636
156050212
3272999680
302120993
0
这个才是我的拿手绝技,哈哈,见笑了。
|
|
|
|
|
|
|
| |
本周最热论坛帖子
|