cftmon
cftmon

Reputation: 203

What does this line of code do?

for (nbyte=0; nbyte<6; nbyte++) {
    mac->byte[nbyte] = (char) (strtoul(string+nbyte*3, 0, 16) & 0xFF);
}

This is a small piece of code found in macchanger, string is a char pointer that points a MAC address, what i don't know is that why must i convert it to a unsigned long int,and why must i *3 then AND it with 0xFF.

Upvotes: -1

Views: 226

Answers (3)

Doug T.
Doug T.

Reputation: 65629

string+nbyte*3

string is a pointer to char (as all C strings are). When you add an integer, x, to a pointer you get the location pointer+x. By adding nbyte*3 you add 3 to pointer, then 6, then 9th,

strtoul converts strings to integers. Specifically here, by passing 16, its specifying base 16 (hex) as the format in the string. Here by passing nbyte*3, your pointer points to the substring beginning at the 3rd, 6th, 9th, etc character of string.

Afte the conversion at each location, the & 0xFF unsets any bits past the 8 LSB, then casts that value to a char.

The result is then stored in a location in the byte array.

Upvotes: 2

Marc B
Marc B

Reputation: 360842

Most likely the string is a mac address in the form of

XX:YY:ZZ:AA:BB:CC

Doing nbyte*3 moves the "starting offset" pointer up 3 characters in the string each iteration, skipping over the :. Then strotoul reads 16bits (2 characters) and converts them to an unsigned long, which is then ANDed with 0xFF to strip off all but the lowest byte, which gets cast to a char.

Upvotes: 4

Mark Byers
Mark Byers

Reputation: 839054

It's parsing from a hexadecimal string, The third parameter of strtoul is the base of the conversion (16 in this case). The input is presumably in this form:

12:34:56:78:9a:bc

The pointer is incremented by 3 each time to start at each pair of hexadecimal digits, which are three apart including the colon.

I don't think the & 0xFF is strictly necessary here. It was presumably there to attempt to correctly handle the case where an input contains a number larger than 0xFF, but the algorithm will still fail for this case for other reasons.

Upvotes: 3

Related Questions