Valhalla Legends Forums Archive | C/C++ Programming | What is Best way to get BYTE values from WORDS? or other values(c++)

AuthorMessageTime
LordVader
Say i had a DWORD..
[code]
(DWORD)szDWord = 1a2b;     
[/code]
szDWord contains BYTE's 1a & 2b

Can someone give me a small example of how I could go about getting the individual bytes from that dword value?

I'm assuming a for or while loop but unsure not had luck with it yet.
May 28, 2005, 6:09 AM
K
I'm not sure why you'd prefix a DWORD with "sz", but other than that...

[code]
typedef unsigned char uint8_t;
DWORD dwFoo = 0xABCD0123;
uint8_t* bytes = (uint8_t*)&dwFoo;

for(int i = 0; i < 3; ++i)
{
  std::cout << "bytes[" << i << "] = " << (int)bytes[i] << std::endl;
}
[/code]
May 28, 2005, 8:18 AM
UserLoser.
[code]
#define LOBYTE(w)           ((BYTE)((DWORD_PTR)(w) & 0xff))
#define HIBYTE(w)           ((BYTE)((DWORD_PTR)(w) >> 8))

WORD TestValue = 0xAB12;
printf("First 8 bits: %02x\r\n", HIBYTE(TestValue));
printf("Last 8 bits: %02x\r\n", LOBYTE(TestValue));
[/code]

May 28, 2005, 5:39 PM
LordVader
ty guys, and the sz is just a short tag i use on variables, habit..

I'll try those methods out should work for what im doing.
I'd looked at using <<|>> right|left shifts but wasn't sure how to empliment, that will be very handy, Ty Both.
May 29, 2005, 8:08 AM
K
[quote author=LordVader link=topic=11712.msg114037#msg114037 date=1117354083]
ty guys, and the sz is just a short tag i use on variables, habit..

I'll try those methods out should work for what im doing.
I'd looked at using <<|>> right|left shifts but wasn't sure how to empliment, that will be very handy, Ty Both.
[/quote]

"sz" is hungarian notation for "string, zero terminated," which is why I mentioned it.    Usually "sz" is used only as a prefix for a char* variable which is terminated by a null character.  The prefix for a double word type variable is usually "dw" -- ie, "dwFlags" pr "dwCharSet".
May 29, 2005, 8:28 AM
Kp
Just so readers are aware: a DWORD is not a double word on modern hardware.  It is a single word (and WORD is actually a half word) -- both on ia32, of course.  On an IA64, DWORD is actually a half word and WORD is a quarter word.
May 29, 2005, 5:05 PM
shout
[code]
DWORD dwNum = 0xAABBCCDD;
BYTE *bytes = &dwNum;
[/code]

bytes[0] = 0xDD
bytes[1] = 0xCC
bytes[2] = 0xBB
bytes[3] = 0xAA

Now what if, for some unknown random reason, wanted the last byte values first simply:

[code]
DWORD dwNum = 0xAABBCCDD;
BYTE bytes[4];

for(int i=0, j=4; i<4; i++, j--)
       bytes[i] = (BYTE *)dwNum[j];
[/code]

Of course, this is for little-edian systems.
June 1, 2005, 4:16 PM

Search