Answer to Question #246383 in C for gryffin

Question #246383

Store a 256-bit unsigned integer number on a 32 byte character array. Add two such

256-bit numbers and print the result.


1
Expert's answer
2021-10-05T06:46:56-0400
#include <stdio.h>

// Little-endian
typedef unsigned char Int256[32];

void print_hex(Int256 x) {
    int i;

    printf("0x");
    for (i=31; i>=0; i--) {
        printf("%02X", x[i]);
    }
}


void add(Int256 a, Int256 b, Int256 c)
{
    int i, part_sum, carry;

    carry = 0;
    for (i=0; i<32; i++) {
        part_sum = a[i] + b[i] + carry;
        c[i] = part_sum % 256;
        carry = part_sum / 256;
    }
}

int main()
{
    Int256 a = { 101, 102, 103, 104, 105, 106, 107, 108,
                 109, 110, 111, 112, 113, 114, 115, 116,
                 117, 118, 119, 120, 121, 122, 123, 124,
                 125, 126, 127, 128, 129, 130, 131,  32};                
    Int256 b = { 201, 202, 203, 204, 205, 206, 207, 208,
                 209, 210, 211, 212, 213, 214, 215, 216,
                 217, 218, 219, 220, 221, 222, 223, 224,
                 225, 226, 227, 228, 229, 230, 231,  32};                
    Int256 c = {0};

    add(a, b, c);

    printf("  ");
    print_hex(a);
    printf("\n+ ");
    print_hex(b);
    printf("\n= ");
    print_hex(c);
    printf("\n");
    
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS