简体   繁体   English

如何从两个 n 位二进制数创建一个 2n 位二进制数?

[英]How can i create from two n-bit binary numbers a 2n-binary number?

Lets suppose i have n=4 so two 4-bit binary numbers.假设我有 n=4 所以两个 4 位二进制数。 B1 = b1010 and B2 = b0110 . B1 = b1010B2 = b0110
I want to create an 8-bit number that looks like this b10100110 (B1B2).我想创建一个类似于b10100110 (B1B2) 的 8 位数字。
How can i do such a thing in Java?我怎么能用Java做这样的事情?

Multiply one by 16 , which is the same as adding four zeroes to the end.将 1 乘以16 ,这与在末尾添加四个零相同。 Then add them.然后添加它们。 In general, multiplying by 2^n adds n zeroes .通常,乘以2^n会添加n zeroes

You can of course multiply and add them as suggested.您当然可以按照建议将它们相乘和相加。 I prefer using bit manipulation operators.我更喜欢使用位操作运算符。

       int b1 = 0b1010;
       int b2 = 0b0110;

       // shift b1 left 4 bits and then OR it with b2.
       int result = (b1<<4)|b2;

       System.out.println(Integer.toBinaryString(result));

As a side note, for every bit you shift left, you are multiplying by a power of 2. So shifting left by 4 bits is multiplying by 16. For right shifting, you are dividing by powers of 2.作为旁注,对于您左移的每一位,您都乘以 2 的幂。因此,左移 4 位就是乘以 16。对于右移,您正在除以 2 的幂。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建一个二进制搜索树,其中包括从1到n的所有数字 - How to create a binary search tree that includes all numbers from 1 to n 如何将N个字符串编码为具有最小位数的二进制数 - How to encode N strings to binary numbers with minimum number of digits 如何创建实现递归二进制搜索以在数组中搜索n个数字的循环? JAVA - How do i create a loop that implement a recursive binary search to search for n numbers in a array? JAVA 如何将十进制数转换为正好8位的二进制数? - How I can convert a decimal number to exactly 8 bit binary? 从线性时间中两个大小均为N的二进制堆中构造大小为2N的二进制堆? - Construct a binary heap of size 2N from two binary heaps each of size N in linear time? 我如何获得最小数量的ArrayList <Integer> 需要具有从1到“ n”的所有数字吗? - how I can get the minimum number of ArrayList<Integer> needed to have all numbers from 1 to “n”? 将数字n分为两个数字,使得两个数字的和为n - Divide a number n into two numbers such that sum of two numbers is n 如何形成一个包含从 0 到 n 的数字的字符串 - How can I form a string containing numbers from 0 to n 计算具有相同属性的两个给定二进制数之间存在多少个X位数为1位的二进制数 - Calculate how many binary numbers with X number of 1 bits exist between two given binary numbers with the same property 通过连接前 n 个自然数的二进制表示形成的数字的十进制值 - decimal value of the number formed by concatenating the binary representations of first n natural numbers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM