Click here to Skip to main content
15,905,504 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This sounds so easy to do but I (probably stupidly) can't workout how to do it in

I have a byte array of 32 bytes and all I want to do is add a byte to it.



plus 00000001 becomes


What I have tried:

I first thought I could just add to the last byte in the array, but at times it will need to be carried over into the next byte.

I also tried converting it into an Integer, but 32 bytes can often exceed the largest Integer limits.
Updated 11-Dec-17 20:22pm
Afzaal Ahmad Zeeshan 11-Dec-17 14:23pm    
So? What is the question?

001 + 001 = 010 in binary, where 1 is carried over to the next addition and so on. Consider reading a bit about the binary number system and arithmetics for it.
codetowns 11-Dec-17 14:59pm    
Yes, but what happens when 11111111 has 1 added to it? The subsequent byte would then need to be added to.

Is the only solutions to iterate each byte until there is no contribution from the last one?
Richard MacCutchan 11-Dec-17 15:23pm    
Create a new array one byte larger, and copy the old to the new.

1 solution

I assume you are writing a "binary" data type of some form: if so, the simplest solution is to handle it in a loop and do the math yourself:
byte[] inp = new byte[32] { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1 };
byte b = 1;
for (int i = 31; i >= 0; i--)
    b += inp[i];
    inp[i] = (byte)(b % 2);
    b = (byte)(b / 2);

Sorry the dots were supposed to show total width as up to 8*32=256 bits. I didn't explain myself well enough.

Ah... details are important!
That makes it simpler:
byte[] inp = new byte[32] { ... };
int carry  = 1;   // Value to add on.
for (int i = 31; i >= 0; i--)
    carry += inp[i];
    inp[i] = (byte)carry;
    carry >>= 8;
Share this answer
codetowns 12-Dec-17 11:46am    
Thanks. My C# is poor but I think I understand the idea - I have to loop it and add it manually.
OriginalGriff 12-Dec-17 11:53am    
Yes - but is there a good reason why you are doing this? It's a bit of a cack-handed way to do binary yourself! :laugh:
codetowns 12-Dec-17 12:23pm    
Cack-handed is right! It revolves around the fact that I have a 32 Byte array which I have to add a byte to. I'm surprised .NET doesn't let me do it in one line!
OriginalGriff 12-Dec-17 12:35pm    
Yeah - but why do you have 32 bytes to store 32 bits? Why not store them in an integer (32 bits) and cut out the middle man?

That's why .NET doesn't do anything for you here - it's a strange (and very inefficient) way to store info.
codetowns 12-Dec-17 14:38pm    
No, it's 32 bytes with 8 bits in each byte.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900