I am trying to take the end result of a program a little farther and break it up into 4 sections. The program converts a hexadecimal number to binary. I want to take the binary number and break it up into 4 different sections. The sections are 2,7,3,4. Example would be breaking up 0100000110001001 into 01|0000011|000|1001. I am going to assign each of the sections to variables n1,n2,n3,and n4. The end result would be n1=01, n2=0000011, n3=000, and n4=1001. What would be the best way of going through this? I am currently using c++ but can switch to something else if it is easier. Thanks
Asked
Active
Viewed 73 times
-1
-
1The best way to do this is to open [a good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and learn how to use C++ bitwise operators to do this task. – Sam Varshavchik Oct 01 '18 at 01:12
-
Shift and `and`, shift and `and`. – David C. Rankin Oct 01 '18 at 01:14
2 Answers
1
You can use a combination of the >>
(right-shift operator) and &
(Boolean and operator) to accomplish this.
#include <iostream>
#include <bitset>
int main(){
int i = 0b0100000110001001;
int n4 = i & 0b1111;
std::cout << "n4 = " << std::bitset<4>(n4) << '\n';
i = i >> 4;
int n3 = i & 0b111;
std::cout << "n3 = " << std::bitset<3>(n3) << '\n';
i = i >> 3;
int n2 = i & 0b1111111;
std::cout << "n2 = " << std::bitset<7>(n2) << '\n';
i = i >> 7;
int n1 = i & 0b11;
std::cout << "n1 = " << std::bitset<2>(n1) << '\n';
}
Output:
n4 = 1001
n3 = 000
n2 = 0000011
n1 = 01

P.W
- 26,289
- 6
- 39
- 76
0
Well, you can parse your binary number to string then use substring to get the 4 number sections. You may have an issue with the left zeros, that will be discarted by int variables. I made it in C#.
class Program
{
static void Main(string[] args)
{
string binaryNumber = "0100000110001001"; // your binary number to string
int n1 = Convert.ToInt32(binaryNumber.Substring(0, 2));
int n2 = Convert.ToInt32(binaryNumber.Substring(2, 7));
int n3 = Convert.ToInt32(binaryNumber.Substring(9, 3));
int n4 = Convert.ToInt32(binaryNumber.Substring(12, 4));
string xn1 = n1.ToString().PadLeft(2, '0');
string xn2 = n1.ToString().PadLeft(7, '0');
string xn3 = n1.ToString().PadLeft(3, '0');
string xn4 = n1.ToString().PadLeft(4, '0');
Console.WriteLine("Numbers in INT variables (without left zeros)");
Console.WriteLine($"1 Section (2):{n1}");
Console.WriteLine($"2 Section (7):{n2}");
Console.WriteLine($"3 Section (3):{n3}");
Console.WriteLine($"4 Section (4):{n4}");
Console.WriteLine("Numbers in STRING variables (with left zeros)");
Console.WriteLine($"1 Section (2):{xn1}");
Console.WriteLine($"2 Section (7):{xn2}");
Console.WriteLine($"3 Section (3):{xn3}");
Console.WriteLine($"4 Section (4):{xn4}");
Console.ReadKey();
}
}
Hope it helps!

R. Paiva
- 43
- 4
-
While converting to a string and then parsing the string will work, AND and right shift will chop the number up in a fraction of the time. – user4581301 Oct 01 '18 at 04:55