简体   繁体   中英

How do I use C# to convert int to bytes that only use the low 4 bits?

I have a conversion problem in C#. Basically, I'm trying to convert an integer to bytes so that we only use the low 4 bits. Example 255 = 0F 0F or:

0xpqrs = 0p 0q 0r 0s

5*16*16*16 + 1*16*16 + 15*16 + 1  = 05 01 0f 01

How do I implement this in C#?

int => bytes:

int value = 0x51f1;
byte s = (byte)(value & 0xf);
byte r = (byte)(value>>4 & 0xf);
byte q = (byte)(value>>8 & 0xf);
byte p = (byte)(value>>12 & 0xf);

bytes => int:

int value = p<<12 | q<<8 | r<<4 | s;

Lucero's answer modified to work in a loop with longer integers.

    public static byte[] intToBytesV2(ulong l)
    {
        byte[] theBytes = new byte[8];
        for (int i = 0; i < 8; i++) {
            theBytes[i] = (byte)(l >> (i * 4) & 0xf);
        }
        return theBytes;
    }

pom =)

byte [] bArray = System.BitConverter.GetBytes(i);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM