Rabbit_KIm
Rabbit_KIm

Reputation: 3

How do I divide 8 byte integer to four 2 bytes Hexadecimal in C?

I've got school task but IDK How to design the code at all...

The function that it need to do is,

  1. input 8 byte integer (I think it has to be unsigned long long type, cause input number has to be 0 or more)

  2. divide input number to four 2 bytes and save it each variable. <<for example, input number is 18446744073709551615 then, it will be 1111111111111111111111111111111111111111111111111111111111111111 in binary. (it doesn't have to convert to binary, just show you how to divide) divide like this 1111111111111111 / 1111111111111111 / 1111111111111111 / 1111111111111111 in four part>>

  3. and make each part to hexadecimal <like this, 1111111111111111 / 1111111111111111 / 1111111111111111 / 1111111111111111 -> ffff / ffff / ffff / ffff>

  4. finally, make ffff / ffff / ffff / ffff to decimal number 65535 / 65535 / 65535 / 65535

Sorry, for my bad English but I need your help so bad.... ;( My level is quite low so when you explain I need some example codes to see and understand.

Thank you for reading my question!

Upvotes: 0

Views: 448

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 223484

Supposing a byte is the eight-bit byte vulgaris, an eight-byte integer is 64 bits. Then:

  1. Include <inttypes.h> and <stdint.h>.
  2. Define a 64-bit unsigned integer variable x using uint64_t from <stdint.h>.
  3. Use scanf("%" SCNu64, &x) to read the number from input.
  4. Test the return value of scanf. If it is not 1, for one number read, print an error message and exit the program.
  5. The four parts of the number are the 16 bits at each of the bit positions 0, 16, 32, and 48. Right-shift x by 0, 16, 32, and 48 to move each part to the low bits.
  6. After each shift, extract the low 16 bits. You can do this with an AND operation with a 16-bit mask, 0xffffu, or you can do it by assigning the value to a uint16_t variable, which stores only 16 bits.
  7. Print the numbers. If you have them in a uint16_t variable, you can print them with printf("%" PRIu16, variable);. If they are in some other variable or type of expression, you need a different conversion specifier, such as PRIu64 if you have a uint64_t expression.

Upvotes: 1

Related Questions