1

I got a task to rewrite C# code in NodeJs. Unfortunately there are some nasty oneliners in that function which I do not fully understand.

Code

int b, sign = ((b = byteBuffer.ReadByte()) >> 6) & 1, i = b & 0x3F, offset = 6; 

Question

I can see that there are multiple assignments, but I am not sure what values these variables are supposed to have.

Could someone explain this oneliner and/or rewrite it into a simpler to understand C# snippet?

11
  • 2
    "these two variables", since the line declares 4 variables, which two are you talking about in particular? Commented Apr 23, 2019 at 21:36
  • Oh then ignore this (gonna edit it). I thought these were just 2 variables, I simply didn't understand that it declares 4 variables Commented Apr 23, 2019 at 21:37
  • Also, assuming byteBuffer is a Stream, can't you simply copy and paste this line of code into your C# code? Commented Apr 23, 2019 at 21:37
  • 2
    Not only are they hard to understand, the author has also seemingly made it even harder because he first declares the b variable, then assigns to it as part of the next variable declaration. It would make much more sense as int b = byteBuffer.ReadByte(), sign = (b >> 6) & 1, i = b & 0x3f, offset = 6;, that is, if we still want to keep it as a oneliner. Commented Apr 23, 2019 at 21:40
  • 1
    @RufusL Yeah, much clearer. ;) Commented Apr 23, 2019 at 22:02

1 Answer 1

4

Basically, it's the same as

int b = byteBuffer.ReadByte(); int sign = (b >> 6) & 1; int i = b & 0x3F; int offset = 6; 

In detail:

In the original line, each top-level , splits the declaration:

int b, sign = ((b = byteBuffer.ReadByte()) >> 6) & 1, i = b & 0x3F, offset = 6; ^here ^here ^ here 

and then you're left with a tricky :

int b; int sign = ((b = byteBuffer.ReadByte()) >> 6) & 1; // ... 

which in fact first defines B as without initial value, but then the next expression immediatelly assigns the result of 'ReadByte' to the B as the first sub-operation, so in fact it's the same as initializing B with it from the start, and you end up with what I wrote in the first code snippet.

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

3 Comments

Holy moly, I am glad there is Stack Overflow with such a great C# community. Thank you for your detailed explanation!
You thank people by clicking the green checkmark at the upper-left of their answer.
@DourHighArch Not possible within 15 minutes ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.