9

I inherited some code and can't figure out one piece of it:

byte[] b = new byte[4] { 3, 2, 5, 7 };
int c = (b[0] & 0x7f) << 24 | b[1] << 16 | b[2] << 8 | b[3];

Can anyone tell what's happening here?

3
  • You want to give us a little context about where you found this code? Or is this just a test? Commented Aug 9, 2011 at 17:53
  • @Nix is where he got it really relevant? Commented Aug 9, 2011 at 17:57
  • @MGZero now that it has been answered no.. Commented Aug 9, 2011 at 17:58

2 Answers 2

20

Basically it converts the lower 31 bits of a 4 byte array into an integer using a big-endian conversion.

So a byte array of { 0, 0, 0, 1 } would be converted to 1; a byte array of { 0, 0, 1, 0 } would be converted to 256 etc.

It does this through a mixture of bitwise operators:

Sign up to request clarification or add additional context in comments.

4 Comments

Any detailed info on this? Links, etc. I'd appreciate that.
@Kizz: I was just editing with links for each operator. What else do you need?
It puzzles me why Stackoverflow won't let me accept an answer for a certain period of time?
@MTG: So that it gives an opportunity for someone to post a better one.
5

haven't done bit math in a minute so..for fun:
[extra parenthesis to show order of ops]

((b[0] & 0x7f) << 24) | (b[1] << 16) | (b[2] << 8) | b[3]

(b[0] & 0x7f) << 24 =  11 0000 0000 0000 0000 0000 0000
b[1] << 16 = . . . . . . . . . . 10 0000 0000 0000 0000
b[2] << 8 = . . . . . . . . . . . . . . . 101 0000 0000
b[3] = .  .  .  .  .  .  .  .  .  .  .  .  .  .  . 0111

now OR these together, and you get

0011 0000 0010 0000 0101 0000 0111 = 50,464,007

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.