Given two 32-bit integers, N and M, and I and j, which represent bit positions. Write a method to insert m into N, * so that M starts from the J-bit of N and ends with the I-bit.

Source: Internet
Author: User
1/* 2 * Two 32-bit integers n and m are given, and I and j represent bit positions. Write a method to insert m to n. 3 * starts m from the J-bit of N to the end of the I-bit. It is assumed that M is sufficient from the J-bit to the I-bit, that is, M = 10011 4 *. Then, J and I can accommodate at least five numbers. If J = 3, I = 2 is not possible, because M 5*6 * n = 1000000000 (1024) 7 * m = 10011 (19) 8 * I = 2, j = 6, output 10001001100 9 * ideas: 10*1. clears from J to I in N by 11*2. perform the shift operation on m and the bit between J and I to perform the 12*3 operation on M. merge m and N13 **/14 public int updatebits (int n, int M, int I, Int J) 15 {16 int allones = ~ 0; // create a series of 1 For example: 1111111117 int left = allones <(J + 1); // The average bit before position J is 1, and the remaining is 0, it is 1110000018 int right = (allones <I)-1) at the moment; // After position I, the bits are set to 1, and the current value is 0000001119 int mask = left | right; // After bitwise OR operation, get the 1110001120 int n_cleared = N & mask; // clear the position J to the I bit, and then put m in the 21 int m_shifted = m <I; // move m to the corresponding location 22 return n_cleared | m_shifted; // bitwise OR operation 23 24} 25 public static void main (string [] ARGs) {26 // todo auto-generated method stub27 bitget BG = new bitget (); 28 int num = BG. updatebits (1024, 19, 2, 6); 29 system. out. println (integer. tobinarystring (Num); 30 31}

 

Given two 32-bit integers, N and M, and I and j, which represent bit positions. Write a method to insert m into N, * so that M starts from the J-bit of N and ends with the I-bit.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.