English 中文(简体)
• 如何学习比喻业务[闭门]
原标题:How to Learn Bitwise operation [closed]

这个问题似乎并不涉及在help Center中界定的范围之内的方案规划。

Closed 3 hours ago.

我没有像现在这样面临两难行动的问题:

Generate mask indicating leftmost 1 in x. Assume w=32.
For example, 0xFF00 -> 0x8000, and 0x6600 -> 0x4000.
If x = 0, then return 0.

The question also sets the limits that only using bitwise operations and "-" "+" to solve the problem. Here s detail:

隐蔽

Conditionals (if or ?:), loops, switch statements, function calls, and macro invocations. Division, modulus, and multiplication. Relative comparison operators (<, >, <=, and >=).

允许的行动

All bit-level and logic operations. Left and right shifts, but only with shift amounts between 0 and w – 1. Addition and subtraction. Equality (==) and inequality (!=) tests. (Some of the problems do not allow these.) Integer constants INT_MIN and INT_MAX. Casting between data types int and unsigned, either explicitly or implicitly.”

我可以理解这些问题的解决办法。 但是,我第一次没有接触过。 这是否意味着我缺乏任何知识,例如离散的数学? 是否有任何来源来开展高效的双向行动?

问题回答

在这里,我们采取了一种冷静的做法:

  • Initialize a 32 bit unsigned integer, m, with only the highest bit set (1u << 31).
  • Loop until m reaches 0, right shifting it one step at the end of every iteration.
  • In the loop, check if m & value_to_check (bitwise AND) is non-zero. If it is, break out.
  • After the loop, m will have the leftmost bit in value_to_check set (or be zero if value_to_check was zero).




相关问题
Fastest method for running a binary search on a file in C?

For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Tips for debugging a made-for-linux application on windows?

I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

Encoding, decoding an integer to a char array

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...

热门标签