0

Is this code workable? I need to extract the upper byte and lower byte from array which consist of Hex codes. For example, in 0x0604 I need 6 in upper byte and 4 in lower byte and lower byte will not exceed by 7.

unsigned int TestArray[3] = {0x0604, 0x0605, 0x0606};

void TestRoutine(unsigned char Number)
{
    unsigned char Data = TestArray[Number];
    unsigned char UpperByte = (Data/256); //upper byte
    unsigned char LowerByte = (Data%256 & 0x07); //lower byte
}
MICRO
  • 253
  • 2
  • 9
  • In `unsigned char Data = TestArray[Number];` how do you expect to work with values > `0xFF`? You have already truncated the value. Work with `unsigned int Data`. And your lower byte is over complicated, try `LowerByte = Data & 0x07;` – Weather Vane Sep 14 '16 at 10:32
  • So using mod(%) will complicate ? How? – MICRO Sep 14 '16 at 10:39
  • By performing unnecessary computation. – Weather Vane Sep 14 '16 at 10:40
  • @WeatherVane I have another query, how this piece of code will work. This is in the same context to above question. What will DATA char array will store and how shifting is happening. `unsigned char DATA[24];` `DATA[UpperByte] |= (0x01)< – MICRO Sep 14 '16 at 22:06
  • I am sorry I do not understand, you said you "need 6 in upper byte" and indeed every value has a 6 in the upper byte, so what is an array for? On the other hand, if you meant 6 *bits* in the upper byte, then an array `DATA[24]` is not large enough, it would need to be `DATA[64]`. But please ask another question showing what you have tried. – Weather Vane Sep 15 '16 at 16:50

1 Answers1

3

It's mostly fine except data is too limited to hold a value from the array.

But using explicit shifts and masks only is more typical:

void TestRoutine(unsigned char Number)
{
    const unsigned int data = TestArray[Number];
    const unsigned char UpperByte = data >> 8; //upper byte
    const unsigned char LowerByte = data & 0x7; //lower byte, limited to three bits
}

I edited back the requirement that the lower byte be kept at most 7.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • "Lower byte will not exceed 7" – Weather Vane Sep 14 '16 at 10:37
  • `LowerByte` and `UpperByte` could be the other way around, depending on endianness. – Blagovest Buyukliev Sep 14 '16 at 10:39
  • 3
    @BlagovestBuyukliev, left and right shift doesn't depend of endiannes: http://stackoverflow.com/q/7184789/1606345 – David Ranieri Sep 14 '16 at 11:07
  • Yes, the `TestArray` makes it appear (at first glance) like OP is parsing a byte array or something similar, but this code is just taking a single 16-bit integer and extracting high and low bytes. – vgru Sep 14 '16 at 11:13
  • @BlagovestBuyukliev No, it's an array of `unsigned int`, that's never being manipulated using raw byte pointers to memory, so endianness doesn't matter. – unwind Sep 15 '16 at 08:21