ace007
ace007

Reputation: 577

replacing 1st digit with second digit in a byte

What I'm trying to do is loop through the values in the byte array getting the first digit of each value and swapping its place with the second digit, so 35 would be 53 and 24 would be 42.. I can almost do this but i have to convert everything to strings and that seems a little overkill

I've tried it for a while but so far I've only figured that I can convert everything to a string and then work on them, just seems a little clunky..

Upvotes: 1

Views: 329

Answers (2)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137418

It sounds like you want to swap the high and low nibble in each byte.

0x35; // High nibble = 3,  Low Nibble = 5

To do this, you want to shift the high nibble right 4 bits (to make it the low nibble), and shift the low nibble left 4 bits (to make it the high nibble).

var ar = new byte[] { 0x35, 0x24 };

for (int i=0; i<ar.Length; i++) {
    byte b = ar[i];
    b =  (b>>4) | ((b&0x0F)<<4);
    ar[i] = b;
}

Upvotes: 9

Nikola Davidovic
Nikola Davidovic

Reputation: 8656

byte nmbBase =16; //or any other 10 for decimal
byte firstDigit = number /nmbBase;
byte secondDigit = number % nmbBase;
number = secondDigit*numberBase + firstDigit;

This is from cellphone,sorry for any mistakes. You should get in which direction you should go.

Upvotes: 1

Related Questions